<?php
            
use app\model\Record; 
use app\model\Ad; 
use app\model\Comm; 
use app\model\Theme; 
use app\model\Poster; 
use app\model\Worker; 
use app\model\Userdata; 


/**
 * Author: cbw
 * Desc: 教培
 * Time: 2021/11/13 1:42 下午
 * Email: 17854288794@163.com
 */
require_once PATH_MODULE .'define.php';
class EducationModel extends PluginModel {

    public static function getUserFlagBySjId($themeid,$sjid,$page,$type=1)
    {
        $c_arr = [
            ['title'=>'全部','c_id'=>0,'total'=>0]
        ];
        //获取商家下的全部课程
        $sj_courses = self::getCourseList($themeid,$sjid,'',0,0,0,'',0);
        $c_total = 0;
        foreach ($sj_courses as $k => $v){
            $item_total = self::getPayOrderCourseTotal($themeid,$v['id'],$v['shangjia_id']);
            $c_total+= $item_total;
            $tmp_arr = ['title'=>$v['name'],'c_id'=>$v['id'],'total'=>$item_total];
            array_push($c_arr,$tmp_arr);
        }
        $c_arr[0]['total'] = $c_total;
        if ($type==1){
            return $c_arr;
        }else{
            $page_index = max(1,intval($page));
            $page_size = 50;
            $page_start = ($page_index-1)*$page_size;
            $sj_courses_lists = self::getUserCourseFlag($themeid,$sjid,'',0,0,'','',0);
            $sj_courses_list = self::getUserCourseFlag($themeid,$sjid,'',$page_start,$page_size,'','',0);
            $max_page = ceil($sj_courses_lists/$page_size);
            foreach ($sj_courses_list as $k => $v){
                if ($v['status'] && $v['workerid']){
                    $check_worker = db_get(t_worker,['themeid'=>$themeid,'uid'=>$v['workerid']]);
                    $sj_courses_list[$k]['verify_name'] = $check_worker['username']?$check_worker['username']:'';
                    $sj_courses_list[$k]['updated_at'] = $check_worker['username']?$v['updated_at']:'';
                }
            }
            return  $sj_courses_list;
        }
    }

    public static function getUserCouponBySjId($themeid,$sjid,$page,$type=0)
    {
        $c_arr = [
            ['title'=>'全部','c_id'=>0,'total'=>0]
        ];
        $sj_coupons = self::getCouponList($themeid,$sjid,'',0,0);
        $c_total = 0;
        foreach ($sj_coupons as $k => $v){
            $item_total = self::getCouponTotal($themeid,$v['id']);
            $c_total+= $item_total;
            $tmp_arr = ['title'=>$v['name'],'c_id'=>$v['id'],'total'=>$item_total];
            array_push($c_arr,$tmp_arr);
        }
        $c_arr[0]['total'] = $c_total;
        if ($type==0){
            return $c_arr;
        }
        $page_index = max(1,intval($page));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        $total = self::getUserCouponFlag($themeid,$sjid,'',0,0,'','',0,true);
        $list = self::getUserCouponFlag($themeid,$sjid,'',$page_start,$page_size,'','',0);
        $max_page = ceil($list/$page_size);
        return  ['total'=>$total,'max_page'=>$max_page,'list'=>$list];
    }

    public static function getCouponTotal($themeid,$id=0,$type='')
    {
        $condition = "";
        if ($type){
            $condition .= " and status='$type'";
        }
        $sql = "select count(*) as cnt from".tablename(t_shangjia_user_coupon).
            " where themeid='$themeid' and coupon_id='$id' ".$condition;
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取用户优惠券 记录 区分类型
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/9/17 17:00
     * @param $themeid
     * @return array[]
     */
    public static function getStatusCouponCount($themeid)
    {
        $status_arr = [
            ['title'=>'全部','status'=>0,'total'=>0],
            ['title'=>'未使用','status'=>1,'total'=>0],
            ['title'=>'已使用','status'=>2,'total'=>0],
        ];
        foreach ($status_arr as $k => $v){
            if (!$v['status']){
                $sql = " select count(*) as cnt from ".tablename(t_shangjia_user_coupon)." where themeid='$themeid'";
            }else{
                $status = $v['status'];
                $sql = " select count(*) as cnt from ".tablename(t_shangjia_user_coupon)." where themeid='$themeid' and status='$status'";
            }
            $status_arr[$k]['total'] = db_find($sql)['cnt'];
        }
        return $status_arr;
    }

    /**
     * Desc:重建前端缓存数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/4 11:43
     * @param $themeid
     * @param $sj_id
     */
    public static function reBuildSjDetailCache($themeid,$sj_id)
    {
        $cache_key = 'item_'.$themeid.'_'.$sj_id;
        cache_delete($cache_key);
        $val = self::getShangjiaItem($sj_id);
        //获取机构课程
        $sj_course_list = self::getCourseList($themeid,$val['id'],'',0,0);
        $sj_course_total = self::getCourseTotal($themeid,$val['id']);
        $temp_arr = [];
        $item = [
            'name'=>$val['name'],'logo'=>$val['logo'],'topimgs'=>$val['imgs'],
            'card_img'=>$val['card_img'],
            'video'=>$val['videoyouku'],
            'video_back_img'=>$val['video_back_img']?$val['video_back_img']:$val['logo'],
            'content'=>$val['content'],
            'address'=>json_decode($val['address'],true),
            'courses'=>$sj_course_list,
            'address_total' => count(json_decode($val['address'],true)),
            'course_total'=>$sj_course_total,
            'order_total'=>$val['order_total'],
            'kefu'=>['avatar'=>$val['logo'],'mobile'=>$val['mobile'],'name'=>$val['name'].'客服']
        ];
        array_push($temp_arr,$item);
        cache_write($cache_key, $temp_arr);
    }

    public static function insertXnCourseFlag($data)
    {
        $insertid = db_insert(t_shangjia_course_xn_flag,$data);
    }

    public static function getCourseFlagNum($themeid,$course_id)
    {
//        $sql = " select sum(num) as cnt from ".tablename(t_shangjia_course_xn_flag)." where themeid='$themeid' and course_id='$course_id' AND TO_DAYS(created_at) = TO_DAYS(NOW()) ";
        $sql = " select sum(num) as cnt from ".tablename(t_shangjia_course_xn_flag)." where themeid='$themeid' and course_id='$course_id'  ";
        $total =  db_find($sql)['cnt'];
        if ($total<0 || !$total){
            $total = 0;
        }
        return $total;
    }

    public static function getSJXnNum($themeid,$sj_id)
    {
        $sql = " select sum(num) as cnt from ".tablename(t_shangjia_course_xn_flag)." where themeid='$themeid' and shangjiaid='$sj_id' ";
        $total = db_find($sql)['cnt'];
        if ($total<0){
            $total = 0;
        }
        return $total;
    }

    /**
     * Desc:获取贝莱基础首页数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 10:10 上午
     * @return array
     */
    public static function getEducationConfig()
    {
        global $_P, $_G, $_S;
        $system = $_S  = self::getSystem();
        $uid = $_G['member']['uid'];
        if (!$uid){
            exit();
        }

        $themeid = $_P['themeid'];
        $fromuid = $_P['fromuid'];
        $workerid = $_P['workerid'];
        $fans = db_get(t_fans,['uid'=>$uid,'themeid'=>$themeid]);
        $openid = $fans['openid'];

        $theme = Theme::getThemeById($themeid);
        $_C = $config =    Theme::getConfig($themeid);
        $shangjia_list = self::getShangjiaList();
        //机构视频
        $sj_list = [];
        //机构详情
        $sj_detail_list = [];
        foreach ($shangjia_list as $key =>$val){
            $sj_list_data = ['name'=>$val['name'],'logo'=>$val['logo'],'topimgs'=>$val['imgs'],
                'video'=>$val['videoyouku'],'card_img'=>$val['card_img'],
                'video_back_img'=>$val['video_back_img']?$val['video_back_img']:$val['logo']
            ];
            array_push($sj_list,$sj_list_data);
            //获取机构课程
            $sj_course_list = self::getCourseList($themeid,$val['id'],'',0,0);
            $sj_course_total = self::getCourseTotal($themeid,$val['id']);
            $sj_xuni_order_total =self::getSjOrder($val,$themeid);
            array_push($sj_detail_list,
                [
                    'name'=>$val['name'],'logo'=>$val['logo'],'topimgs'=>$val['imgs'],
                    'card_img'=>$val['card_img'],
                    'sj_id'=>$val['id'],
                    'video'=>$val['videoyouku'],
                    'video_back_img'=>$val['video_back_img']?$val['video_back_img']:$val['logo'],
                    'content'=>$val['content'],
                    'address'=>json_decode($val['address'],true),
                    'courses'=>$sj_course_list,
                    'address_total' => count(json_decode($val['address'],true)),
                    'course_total'=>$sj_course_total,
                    'order_total'=>$sj_xuni_order_total,
                    'kefu'=>['avatar'=>$val['logo'],'mobile'=>$val['mobile'],'name'=>$val['name'].'客服']
                ]);
        }
        $sj_list_is_end = false;
        $max_page = ceil(count($shangjia_list)/10);
        if ($max_page==1){
            $sj_list_is_end = true;
        }

        //分页数据
        $shangjia_page_list = self::getShangjiaByPage(0,10);
        //机构视频
        $sj_page_list = [];
        //机构详情
        $sj_page_detail_list = [];
        foreach ($shangjia_page_list as $key =>$val){
            $sj_list_data = ['name'=>$val['name'],'logo'=>$val['logo'],'topimgs'=>$val['imgs'],
                'video'=>$val['videoyouku'],'card_img'=>$val['card_img'],
                'video_back_img'=>$val['video_back_img']?$val['video_back_img']:$val['logo']
            ];
            array_push($sj_page_list,$sj_list_data);
            //获取机构课程
            $sj_course_list = self::getCourseList($themeid,$val['id'],'',0,0,1);
            $sj_course_total = self::getCourseTotal($themeid,$val['id']);
            $sj_xuni_order_total =self::getSjOrder($val,$themeid);
            array_push($sj_page_detail_list,
                [
                    'name'=>$val['name'],'logo'=>$val['logo'],'topimgs'=>$val['imgs'],
                    'card_img'=>$val['card_img'],
                    'sj_id'=>$val['id'],
                    'video'=>$val['videoyouku'],
                    'video_back_img'=>$val['video_back_img']?$val['video_back_img']:$val['logo'],
                    'content'=>$val['content'],
                    'address'=>json_decode($val['address'],true),
                    'courses'=>$sj_course_list,
                    'address_total' => count(json_decode($val['address'],true)),
                    'course_total'=>$sj_course_total,
                    'order_total'=>$sj_xuni_order_total,
                    'kefu'=>['avatar'=>$val['logo'],'mobile'=>$val['mobile'],'name'=>$val['name'].'客服']
                ]);
        }
        //随机5个
        $rand_sj_list = [];
        if (count($sj_detail_list)>=5){
            $tm_rand_sj_list_key = array_rand($sj_detail_list,5);
        }elseif(count($sj_detail_list)>0){
            $tm_rand_sj_list_key = array_rand($sj_detail_list,count($sj_detail_list));
        }

        if ($tm_rand_sj_list_key){
            foreach ($tm_rand_sj_list_key as $key => $val){
                array_push($rand_sj_list,$sj_detail_list[$val]);
            }
        }
        //判断团长身份
        $themyrecord = Record::getLastGroupByUid($uid,$themeid);
        //奖励详情
        $sj_setting = [];
        $item = self::getRewardByWhere(['themeid'=>$themeid]);
        $item['tuan'] = json_decode($item['tuan'],true);
        $item['order'] = json_decode($item['order'],true);
        $item['colors'] = json_decode($item['colors'],true);
        $item['other_name'] = json_decode($item['other_name'],true);
//      获取视频显示位置
        $djs_show = $item['djs_show'];
        $activity_show = $item['activity_show'];
        $flag_show = $item['flag_show'];
        $company_show = $item['company_show'];
        $float_icon_show = $item['float_icon_show'];
        $poster_show = $item['poster_show'];
        $colors = $item['colors'];
        $other_name = $item['other_name'];

        $other_config = json_decode($item['other_config'],true);
        $school_other_name = $other_config['school_other_name'];
        $course_other_name = $other_config['course_other_name'];
        $gift_other_name = $other_config['gift_other_name'];
        $open_position = $other_config['open_position'];
        $open_shangjia_video = $other_config['open_shangjia_video'];
        $show_buy_total = $other_config['show_buy_total'];
        $scrool_icon_show = $other_config['scrool_icon_show'];

        if ($config['iswttouxiang']==9){
            if (empty($_G['address']['province']) || strpos("a".$config['province'].'省', $_G['address']['province']) == false || strpos("a".$_G['address']['province'],'广东' ) !== false){
                $scrool_icon_show =2;
                $activity_show = 2;
                $flag_show = 2;
            }
            if (empty($_G['address']['province'])){
                yxlog($_G['clientip'],'IP查询不到');
            }
        }else{
            if (empty($_G['address']['province']) || strpos("a".$config['province'].'省', $_G['address']['province']) == false || strpos("a".$_G['address']['province'],'广东' ) !== false){
                $scrool_icon_show =2;
                $activity_show = 2;
                $flag_show = 2;
            }
        }


        $edu_share_tips = $other_config['edu_share_tips'];
        $edu_pageshare_txt = $other_config['edu_pageshare_txt'];
        //定位相关
        $edu_location_img = $other_config['edu_location_img'];
        $edu_location_tips = $other_config['edu_location_tips'];
        $edu_location_tips_font_size = $other_config['edu_location_tips_font_size'];
        $edu_location_tips_color = $other_config['edu_location_tips_color'];
        $edu_location_bg_color = $other_config['edu_location_bg_color'];
        $edu_share_img = $other_config['edu_share_img'];
        $edu_location_show = $other_config['edu_location_show'];
        $edu_success_location_tips = $other_config['edu_success_location_tips'];

        $tabcar_ac_info = $other_config['tabcar_ac_info'];
        $tabcar_course_info = $other_config['tabcar_course_info'];
        $tabcar_gift_info = $other_config['tabcar_gift_info'];
        //新增字段
        $company_list_show = $other_config['company_list_show'];
        $tabcar_activity_name = $other_config['tabcar_activity_name'];
        $tabcar_course_name = $other_config['tabcar_course_name'];
        $tabcar_gift_name = $other_config['tabcar_gift_name'];
        $education_acBar_c1_open = $other_config['education_acBar_c1_open'];

        $item_order_count = count($item['order']);
        $temp_arr = [];
        $temp_total_arr = [];
        if ($item['tuan'] && is_array($item['tuan'])){
            foreach ($item['tuan'] as $key => $val)
            {
                if ($val['key']=='主图'){
                    $temp_arr['img'] = $val['val'];
                }
                if ($val['key']=='提供商家'){
                    $temp_arr['shangjia'] = $val['val'];
                }
                if ($val['key']=='奖品'){
                    $temp_arr['title'] = $val['val'];
                }
                if ($val['key']=='价值'){
                    $temp_arr['price'] = $val['val'];
                }
                if ($val['key']=='奖励描述'){
                    $temp_arr['detail'] = $val['val'];
                }
                $temp_arr['from'] = '成团解锁(团长)';
            }
            array_push($temp_total_arr,$temp_arr);
        }

        if ($item['order'] && is_array($item['order'])){
            foreach ($item['order'] as $key => $val){
                $temp_array = [];
                $temp_array['img'] = $val['img'];
                $temp_array['shangjia'] = $val['shangjia_name'];
                $temp_array['title'] = $val['name'];
                $temp_array['price'] = $val['price'];
                $temp_array['from'] = '累计邀请'.$val['invite'].'人解锁';
                $temp_array['detail'] =   db_getcolumn(t_shangjia_gift, array('id' => $val['gift_id']), 'detail');
                array_push($temp_total_arr,$temp_array);
            }
        }
        //赠品list
        $free = self::getGiftList($themeid,0,'',0,0,0,1);
        if ($free && is_array($free)){
            foreach ($free as $key => $val){
                $temp_arr = [];
                $temp_arr['img'] = $val['top_img'];
                $temp_arr['shangjia'] = $val['shangjia_name'];
                $temp_arr['title'] = $val['name'];
                $temp_arr['price'] = $val['price'];
                $temp_arr['from'] = '购买解锁';
                $temp_arr['detail'] = $val['detail'];
                array_unshift($temp_total_arr,$temp_arr);
            }
        }
        //课程列表
        $new_course_list = [];
        $course_list = self::getCourseList($themeid,0,'',0,10);
        foreach ($course_list as $key => $val)
        {
            $temp_arr = [];
            $temp_arr['id'] = $val['id'];
            $temp_arr['name'] = $val['name'];
            $temp_arr['price'] = $val['price'];
            $temp_arr['sales'] = $val['selected_num'];
            $temp_arr['shangjia'] = $val['shangjia_name'];
            $temp_arr['address'] = json_decode($val['address'],true);
            array_push($new_course_list,$temp_arr);
        }
        //判断员工
        $myworker = Worker::getThemeWorkerByOpenid($_G['openid'],$themeid,1);
        //最新订单
        $order_list = self::getFormatOrderList($themeid,$config,50);
//        $order_list = self::get_array_splice($order_list,3);

        //判断优惠券  修改为获取worker_id  找到商家  找独享  找通用  判断时间
        $coupon_item = self::userGetCoupon($themeid,$uid,$workerid);

        //判断海报
        $poster = Poster::getByThemeIdnew($themeid);
        if(!empty($poster['bg'])){
            $config['isposter']=1;
            if ($fans['status']==2 && $system['s']['istubiao']==1) {
                $config['isposter']=0;
            }
            $pm = ['themeid'=>$themeid,'openid'=>$fans['openid']];
            $myposter = db_find("SELECT * FROM ".tablename(t_fans)."
             WHERE themeid = :themeid and openid = :openid",$pm);
            if (empty($myposter['poster'])){
                $waittips = empty($poster['waittips'])?'正在生成海报':$poster['waittips'];
            }else{
                $waittips='';
            }
            //获取海报的url地址
            $posterurl = "/" . createMobileUrl("poster",array("themeid"=>$themeid,"op"=>"action","fromuid"=>$_P['fromuid'],"fopenid"=>$_P['fopenid'],"recordid"=>intval($themyrecord['id'])));

        }else{
            $waittips='海报未开启';
        }

        $pn_wxapp = $_S['pn_wxapp'];
        if (!$pn_wxapp || $pn_wxapp==0){
            //        能否分享
          $canshare = 1;
        //       成功购买后生成
            if ($poster_show==2 && !$myworker && !$themyrecord){
                $waittips = '成功购买课程后，才能生成海报';
                $posterurl = '';
                $canshare = 0;
            }
        }else{
            if ($pn_wxapp==1){
                $canshare = 0;
            }elseif ($pn_wxapp==2){
                $canshare = 1;
            }elseif ($pn_wxapp==3){
                //        能否分享
                $canshare = 1;
                //       成功购买后生成
                if (!$myworker && !$themyrecord){
                    $waittips = '成功购买课程后，才能生成海报';
                    $posterurl = '';
                    $canshare = 0;
                }
            }
        }

        $poster_info = ['tips'=>$waittips,'img_url'=>$posterurl];

        //客服
        $kefu = ['qr_code'=>$config['kfewm'],'mobile'=>$theme['mobile']];
        //底部图片
        $setting = self::getRewardByWhere(['themeid'=>$themeid]);
        //倒计时
        $can_countdown = false;
        $countdown_time = 0;
        $now_time = time();
        if (($theme['begintime']<$now_time) && ($now_time<$theme['endtime']) && $theme['status']=='1') {
            $can_countdown = true;
            $countdown_time = $theme['endtime']-$now_time;
        }
        if ($config['renshu']>0){
            $sql = " select count(*) as cnt from ".tablename(t_record)." where themeid='$themeid' and status=1 ";
            $total = db_find($sql)['cnt'];
            if ($total>=(int)$config['renshu']){
                $can_countdown = false;
            }
        }


        //查找广告信息
        $ad_info = Ad::get_ad_info($config,$fans,$themeid,$themyrecord);
        //判断福利领取记录
        $format_user_flag_list = self::getFormatGiftList($themeid,$config,50);
//        $flag_list = self::getUserGift($themeid,0,'',0,50);
//        foreach ($flag_list as $kk => $vv){
//            $temp_arr = [
//                'avatar'=>$vv['avatar']?$vv['avatar']:'https://css2020.yixuan.net/2020css/yx2020/images/question.png',
//                'nickanme'=>$vv['username']?$vv['username']:$vv['nickname'],
//                'txt'=>'解锁价值'.$vv['price'].'元'.$vv['name'],
//                'status_txt'=>'开团成功',
//                'time'=>date("Y-m-d",strtotime($vv['created_at']))
//            ];
//            array_push($format_user_flag_list,$temp_arr);
//        }
        //跳转地图选点
        $jump_map_url = $_G['siteroot'].createMobileUrl('wx', array('themeid'=>$themeid,'r'=>'education.index.map'));
        //获取用户定位
        $user_map_loc_item = self::getUserMapLoc($themeid,$uid);
        $user_address = '';
        if ($user_map_loc_item){
            $user_address = $user_map_loc_item['poiaddress'];
        }
        return [
            'shangjia_list'=>$shangjia_list,
            'sj_list'=>$sj_list,
            'sj_detail_list'=>$sj_detail_list,
            'item_order_count'=>$item_order_count,
            'temp_total_arr'=>$temp_total_arr,
            'new_course_list'=>$new_course_list,
            'myworker'=>$myworker,
            'coupon_item'=>$coupon_item,
            'poster_info'=>$poster_info,
            'order_list'=>$order_list,
            'kefu'=>$kefu,
            'setting'=>$setting,
            'can_countdown'=>$can_countdown,
            'countdown_time'=>$countdown_time,
            'user_flag_list'=>$format_user_flag_list,//福利领取记录
            'djs_show'=>$djs_show,
            'activity_show'=>$activity_show,
            'flag_show'=>$flag_show,
            'company_show'=>$company_show,
            'float_icon_show'=>$float_icon_show,
            'canshare'=>$canshare,
            'edu_colors'=>$colors,
            'other_name'=>$other_name,
            'open_shangjia_video'=>$open_shangjia_video,
            'open_position'=>$open_position,
            'show_buy_total'=>$show_buy_total,
            'sj_list_is_end'=>$sj_list_is_end,
            'sj_page_list'=>$sj_page_list,
            'sj_page_detail_list'=>$sj_page_detail_list,
            'rand_sj_list'=>$rand_sj_list,
            'ad_info'=>$ad_info,
            'scrool_icon_show'=>$scrool_icon_show,
            'edu_pageshare_txt'=>$edu_pageshare_txt,
            'edu_location_img'=>$edu_location_img,
            'edu_location_tips'=>$edu_location_tips,
            'edu_location_tips_font_size'=>$edu_location_tips_font_size,
            'edu_location_tips_color'=>$edu_location_tips_color,
            'edu_location_bg_color'=>$edu_location_bg_color,
            'edu_share_tips'=>$edu_share_tips?explode(",",$edu_share_tips):[],
            'edu_share_img'=>$edu_share_img,
            'edu_location_show'=>$edu_location_show,
            'edu_success_location_tips'=>$edu_success_location_tips,
            'tabcar_ac_info'=>$tabcar_ac_info,
            'tabcar_course_info'=>$tabcar_course_info,
            'tabcar_gift_info'=>$tabcar_gift_info,
            'course_other_name'=>$course_other_name,
            'company_list_show'=>$company_list_show,
            'tabcar_activity_name'=>$tabcar_activity_name,
            'tabcar_course_name'=>$tabcar_course_name,
            'tabcar_gift_name'=>$tabcar_gift_name,
            'education_acBar_c1_open'=>$education_acBar_c1_open,
            'jump_map_url'=>$jump_map_url,
            'user_address'=>$user_address,
        ];
    }

    public static function getSjOrder($sj,$themeid)
    {
//        $sql = "SELECT sum(record) as xn_total FROM ".tablename(t_workerreport)." WHERE themeid = ".$themeid." and workerid = -" . $sj['id'];
//        $xuni_total = db_find($sql)['xn_total'];
//        return (int)$xuni_total+(int)$sj['order_total'];
        $sql = "SELECT sum(selected_num) as real_total FROM ".tablename(t_shangjia_course)." WHERE themeid = ".$themeid." and shangjiaid = " . $sj['id'];
        $sj_course_real_total = db_find($sql)['real_total'];
        $sj_course_total = self::getSJXnNum($themeid,$sj['id']);
        return $sj_course_total+$sj_course_real_total;
    }

//    public static function get_array_splice($array, $columns)
//    {
//        $columns_map=array();
//        for($i=0;$i<$columns;$i++){
//            $columns_map[]=0;
//        }
//        $array_length=count($array);
//        $position=0;
//        while($array_length>0){
//            $columns_map[$position]++;
//            //这个地方格外注意,$position与$columns比较
//            $position=($position<$columns-1)?++$position:0;
//            $array_length--;
//        }
//        foreach ($columns_map as $val){
//            $new_array[]=array_splice($array,0,$val);
//        }
//        return $new_array;
//    }

    public static function checkThemeStatus($theme)
    {
        $now_time = time();
        if ($theme['begintime']>$now_time) {
            return 0;
        }
        if ($now_time>$theme['endtime']) {
            return 0;
        }
        if ($theme['status']=='2'){
            return 0;
        }
        return 1;
    }

    public static function getPayOrderCourseTotal($themeid,$course,$sj_id)
    {
        $sql = " select count(*) as cnt from ".tablename(t_shangjia_address_user_course)." as a ".
            " left join ".tablename(t_record)." as b on a.order_id = b.id and b.themeid='$themeid' ".
            " where a.themeid=$themeid and a.course_id='$course' and a.shangjiaid = '$sj_id' and b.status=1 ";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:检查活动是否停止
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/3 3:47 下午
     * @param $theme
     * @return bool
     */
    public static function checkThemeEnd($theme)
    {
        $is_end = false;
        $now_time = time();
        if ($now_time>$theme['endtime']) {
            $is_end = true;
        }
        if ($theme['status']=='2'){
            $is_end = true;
        }
        return $is_end;
    }

    /**
     * Desc:判断用户是否存在礼品获得记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/3 6:48 下午
     * @param $themeid
     * @param $gift_id
     * @param $uid
     * @return mixed
     */
    public static function checkUserHasGift($themeid,$gift_id,$uid)
    {
        return db_get(t_shangjia_user_gift,['themeid'=>$themeid,'uid'=>$uid,'gift_id'=>$gift_id,'status'=>2]);
    }

    public static function getUserOrderGiftTotalByWhere($themeid,$status,$order_id,$is_verify)
    {
        $condition = "";
        if ($is_verify){
            $condition .= ' and workerid >0';
        }
        $sql = " select count(*) as cnt from".tablename(t_shangjia_user_gift)." where themeid='$themeid' and status='$status' and order_id='$order_id'".$condition;
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:插入用户赠品
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/5 8:21 下午
     * @param $data
     * @return mixed
     */
    public static function insertUserGift($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_user_gift,$data);
    }

    /**
     * Desc:删除同一订单号下的礼品选择记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/6 9:14 下午
     * @param $where
     * @return mixed
     */
    public static function delUserGiftByWhere($where)
    {
        return db_delete(t_shangjia_user_gift,$where);
    }

    /**
     * Desc:更新用户领取的礼品数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 2:15 下午
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function updateUserGift($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_user_gift,$data,$where);
    }


    /**
     * Desc:检查活动是否开始
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/3 3:49 下午
     * @param $theme
     * @return int|string
     */
    public static function checkThemeStart($theme)
    {
        $is_start = '';
        $now_time = time();
        if ($theme['begintime']>$now_time) {
            $is_start = $theme['begintime']-$now_time;
        }
        return $is_start;
    }

    /**
     * Desc:获取用户获取的赠品记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/3 9:21 下午
     * @param $uid
     * @param $themeid
     * @return mixed
     */
    public static function getFreeFlag($uid,$themeid)
    {
        return db_getall(t_shangjia_user_gift,['uid'=>$uid,'themeid'=>$themeid,'status'=>1,'can_use'=>1]);
    }

    /**
     * Desc:获取好友下单数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/3 7:18 下午
     * @param $themeid
     * @param $from_uid
     * @return mixed
     */
    public static function getFriendOrderTotal($themeid,$from_uid,$is_tuan=false,$pid=0)
    {

        if ($is_tuan){
            if (empty($pid)){
                return 0;
            }
            $sql = " SELECT COUNT(*) AS cnt FROM ".tablename(t_record)." where themeid=$themeid and fromuid=$from_uid and status=1 and pid!=$pid";
        }else{
            $sql = " SELECT COUNT(*) AS cnt FROM ".tablename(t_record)." where themeid=$themeid and fromuid=$from_uid and status=1";
        }

        return db_find($sql)['cnt'];
    }

    /**
     * Desc:查找团长订单
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/7 11:50 上午
     * @param $themeid
     * @param $pid
     * @return mixed
     */
    public static function getTunaGroupItem($themeid,$pid)
    {
        $sql = " select * from ".tablename(t_record)." where themeid=$themeid and pid=$pid and status>0 and isfinish=1";
        return db_find($sql);
    }

    /**
     * Desc:获取团长订单 支付不成团
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/9 09:16
     * @param $themeid
     * @param $pid
     * @return mixed
     */
    public static function getTuanGroupItemByNoFinish($themeid,$pid)
    {
        $sql = " select * from ".tablename(t_record)." where themeid=$themeid and pid=$pid and status>0";
        return db_find($sql);
    }

    /**
     * Desc:获取课程的选择记录数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/28 16:43
     * @param $themeid
     * @param $course_id
     * @return mixed
     */
    public static function getCourseTotalById($themeid,$course_id)
    {
        $sql = " select count(*) as cnt from ".tablename(t_shangjia_address_user_course).
            " where themeid='$themeid' and course_id='$course_id' ";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:支付成功后的
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/4 7:20 下午
     */
    public static function payRollback($themeid,$uid,$order_id)
    {
        $config =  Theme::getConfig($themeid);
        /**
         * 红包发放 禁用
         */
//        self::redPackageOut($themeid,$uid);
        /**
         * 判断成团礼 邀请礼
         */
        $setting = self::getRewardByWhere(['themeid'=>$themeid]);

        $order_item = Record::getLastGroupByUid($uid,$themeid);

        //判断模式
        $other_config = json_decode($setting['other_config'],true);
        $gift_unlock_min_num = $other_config['gift_unlock_min_num'];
        $gift_unlock_max_num = $other_config['gift_unlock_max_num'];
        $lock_gift_mode = $other_config['lock_gift_mode'];
        $lock_gift_type = $other_config['lock_gift_type'];

        if ($lock_gift_type==1){
            //团长处理
            $tuan_head_option = self::tuanHeadOption($themeid,$order_item,$setting,$uid,$order_id);
            //不限制  仅判判断邀请人是否付款
            $fromuid = $order_item['fromuid'];
            //判断邀请人是否是团员
            $from_order_item = Record::getLastGroupByUid($fromuid,$themeid);
            $friend_order_total = (int)self::getFriendOrderTotal($themeid,$from_order_item['uid']);
            if ($friend_order_total && $from_order_item['status']==1){
                $order_gift_info = json_decode($setting['order'],true);
                foreach ($order_gift_info as $key => $val){
                    if ($friend_order_total>=$val['invite']){
                        $order_gift_id = $val['gift_id'];
                        $order_gift = self::getGiftItemById($themeid,$order_gift_id);
                        $check_order_gift = self::checkUserHasGift($themeid,$order_gift_id,$from_order_item['uid']);

                        if (!$check_order_gift){
                            $insert_data = ['order_id'=>$from_order_item['id'],'uid'=>$from_order_item['uid'],'shangjiaid'=>$order_gift['shangjiaid'],
                                'gift_id'=>$order_gift_id,'status'=>2,'can_use'=>1,'themeid'=>$themeid
                            ];
                            $res = self::insertUserGift($insert_data);
                        }
                    }
                }
            }
        }else{
            //团长处理
            $tuan_head_option = self::tuanHeadOption($themeid,$order_item,$setting,$uid,$order_id);
            //团员处理
            $taun_Member_option = self::tuanMemberOption($themeid,$order_item,$setting,$uid,$order_id);
        }



        //更新用户的礼品
        //查询用户已获取的礼品
        $free_gift_item = db_get(t_shangjia_user_gift,['themeid'=>$themeid,'uid'=>$uid,'can_use'=>0]);
        if ($free_gift_item){
            //更新礼品订单号
            $where = ['themeid'=>$themeid,'uid'=>$uid,'can_use'=>0];
            $update_data = ['order_id'=>$order_id,'can_use'=>1];
            $res = self::updateUserGift($where,$update_data);
        }

        //更新用户的选择课程
        $course_where = ['themeid'=>$themeid,'uid'=>$uid];
        $course_data = ['order_id'=>$order_id];
        $res = self::updateUserCourseAddress($course_where,$course_data);
        //更新用户的优惠券
        $user_coupon_item = db_get(t_shangjia_user_coupon,['uid'=>$uid,'themeid'=>$themeid,'status'=>1]);
        if ($user_coupon_item){
            $coupon_item = db_get(t_shangjia_coupon,['id'=>$user_coupon_item['coupon_id']]);
            //判断优惠券是否可用
            $now = date("Y-m-d H:i:s",time());
            if ($coupon_item && ($coupon_item['use_start_time']<=$now) && ($now<=$coupon_item['use_end_time'])){
                //判断当前优惠券是否可使用
                //更新商家优惠券
                $new_use_num = $coupon_item['use_num']+1;
                $where = ['themeid'=>$themeid,'id'=>$coupon_item['id']];
                $update_data = ['use_num'=>$new_use_num];
                $result1 = self::editCouponItem($where,$update_data);
                //更新用户优惠券状态
                $user_coupon_where= ['themeid'=>$themeid,'uid'=>$uid,'id'=>$user_coupon_item['id']];
                $user_coupon_data= ['status'=>2,'order_id'=>$order_id];
                $res1 = self::updateUserCoupon($user_coupon_where,$user_coupon_data);
            }
        }

        //更新课程选择数 商家选择数
        //获取当前用户订单下的课程 以及选择商家
        $user_all_list = self::getUserAllCourseAddress(['order_id'=>$order_id,'themeid'=>$themeid]);
        foreach ($user_all_list as $key =>$val){
            $course_item = self::getCourseItemById($themeid,$val['course_id']);
            $where = ['themeid'=>$themeid,'id'=>$val['course_id']];
            $data = ['selected_num'=>$course_item['selected_num']+1];
            $update = self::editCourseItem($where,$data);
            //更新商家报名
            $shangjia_item = db_get(t_shangjia,['id'=>$val['shangjiaid']]);
            $new_order_total = $shangjia_item['order_total']+1;
            $update_shangjia = db_update(t_shangjia,['order_total'=>$new_order_total],['id'=>$val['shangjiaid']]);
        }
        self::educationCheck($themeid);
    }

    /**
     * Desc:修正商家报名 以及课程选择量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/13 16:24
     * @param $themeid
     */
    public static function educationCheck($themeid)
    {
        $shangjia_list = self::getShangjiaList();
        //更新商家订单
        foreach ($shangjia_list as $k => $v){
            $sql = ' select a.* from '.tablename(t_shangjia_address_user_course)." as a ".
                " left join ".tablename(t_record)." as b on a.order_id = b.id ".
                " where a.themeid=$themeid and a.shangjiaid={$v['id']} and b.status=1 group by a.order_id";
            $order_flag_list = db_select($sql);
            if ($order_flag_list){
                foreach ($order_flag_list as $key => $val){
                    $shangjia_item = db_get(t_shangjia,['id'=>$val['shangjiaid']]);
                    $new_order_total = count($order_flag_list);
                    $update_shangjia = db_update(t_shangjia,['order_total'=>$new_order_total],['id'=>$val['shangjiaid']]);
                }
            }
        }
        //更新课程选择
        $course_sql = "SELECT * FROM ".tablename(t_shangjia_course)." where themeid=$themeid ";
        $course_all = db_select($course_sql);
        foreach ($course_all as $k => $v){
            $sql1 = ' select a.* from '.tablename(t_shangjia_address_user_course)." as a ".
                " left join ".tablename(t_record)." as b on a.order_id=b.id ".
                " where a.themeid=$themeid and a.course_id={$v['id']} and b.status=1 ";
            $order_flag_list1 = db_select($sql1);
            if ($order_flag_list1){
                $course_item = self::getCourseItemById($themeid,$v['id']);
                $where = ['themeid'=>$themeid,'id'=>$v['id']];
                $data = ['selected_num'=>count($order_flag_list1)];
                $update = self::editCourseItem($where,$data);
            }
        }
    }



    /**
     * Desc:团长的处理
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/9 10:11
     */
    public static function tuanHeadOption($themeid,$order_item,$setting,$uid,$order_id)
    {
        $tuan_order_item = db_get(t_record,['themeid'=>$themeid,'id'=>$order_item['pid'],'type'=>0,'status'=>1]);

        if ($tuan_order_item){
            //判断团长身份
            $themyrecord = Record::getLastGroupByUid($tuan_order_item['uid'],$themeid);
        }else{
            $themyrecord = [];
        }
        //判断当前订单的团长
        if ($themyrecord){
            $tuan_group_item = self::getTunaGroupItem($themeid,$themyrecord['pid']);
            //如果没有成团
            if (!$tuan_group_item){
                //查找推荐人是否是团长
                $from_user_themyrecord = Record::getLastGroupByUid($themyrecord['fromuid'],$themeid);
                if (!$from_user_themyrecord){
                    $tuan_group_item =[];
                }else{
                    $tuan_group_item = self::getTunaGroupItem($themeid,$from_user_themyrecord['pid']);
                }
            }
        }else{
            $tuan_group_item =[];
        }

        if ($tuan_group_item && $tuan_group_item['type']==0 && $tuan_group_item['status']>0 && $tuan_group_item['isfinish']==1){
            $tuan_gift_info = json_decode($setting['tuan'],true);
            foreach ($tuan_gift_info as $key => $val){
                if ($val['key']=='id'){
                    $tuan_gift_id = $val['val'];
                }
            }
            $tuan_gift = self::getGiftItemById($themeid,$tuan_gift_id);
            //插入团长礼品
            //检查用户是否存在记录
            $check_tuan_gift = self::checkUserHasGift($themeid,$tuan_gift_id,$tuan_group_item['uid']);

            if (!$check_tuan_gift){
                $insert_data = ['order_id'=>$tuan_group_item['id'],'uid'=>$tuan_group_item['uid'],'shangjiaid'=>$tuan_gift['shangjiaid'],
                    'gift_id'=>$tuan_gift_id,'status'=>2,'can_use'=>1,'themeid'=>$themeid
                ];
                $res = self::insertUserGift($insert_data);
            }
        }


        // 模式1 支付满团 判断邀请人数
        if ($setting['send_gift_type']==1){

            //判断邀请人数
            if ($tuan_group_item && $tuan_group_item['type']==0 && $tuan_group_item['status']>0 && $tuan_group_item['isfinish']==1){
                //判断团长身份
                $friend_order_total = (int)self::getFriendOrderTotal($themeid,$tuan_group_item['uid'],true,$tuan_group_item['pid']);

                if ($friend_order_total){
                    $tuan_gift_info = json_decode($setting['tuan'],true);
                    foreach ($tuan_gift_info as $key => $val){
                        if ($val['key']=='id'){
                            $tuan_gift_id = $val['val'];
                        }
                    }
                    //检查用户是否存在记录
                    $check_tuan_gift = self::checkUserHasGift($themeid,$tuan_gift_id,$tuan_group_item['uid']);

                    if ($check_tuan_gift){
                        //邀请人数的计算  不在同一个团内 计数
//                    $friend_order_total = max(0,($friend_order_total-$config['maxcountall']));

                        //判断是否存在团长礼
                        $order_gift_info = json_decode($setting['order'],true);
                        foreach ($order_gift_info as $key => $val){
                            if ($friend_order_total>=$val['invite']){
                                $order_gift_id = $val['gift_id'];
                                $order_gift = self::getGiftItemById($themeid,$order_gift_id);
                                $check_order_gift = self::checkUserHasGift($themeid,$order_gift_id,$tuan_group_item['uid']);

                                if (!$check_order_gift){
                                    $insert_data = ['order_id'=>$tuan_group_item['id'],'uid'=>$tuan_group_item['uid'],'shangjiaid'=>$order_gift['shangjiaid'],
                                        'gift_id'=>$order_gift_id,'status'=>2,'can_use'=>1,'themeid'=>$themeid
                                    ];
                                    $res = self::insertUserGift($insert_data);
                                }
                            }
                        }
                    }
                }
            }
        }
        // 模式二 支付不满团 判断邀请人数
        if ($setting['send_gift_type']==2){
            //判断当前订单的团长
            if ($themyrecord){
                $tuan_group_item = self::getTuanGroupItemByNoFinish($themeid,$themyrecord['pid']);
                //如果没有成团
                if (!$tuan_group_item){
                    //查找推荐人是否是团长
                    $from_user_themyrecord = Record::getLastGroupByUid($themyrecord['fromuid'],$themeid);
                    if (!$from_user_themyrecord){
                        $tuan_group_item =[];
                    }else{
                        $tuan_group_item = self::getTuanGroupItemByNoFinish($themeid,$from_user_themyrecord['pid']);
                    }
                }
            }else{
                $tuan_group_item =[];
            }
            //判断邀请人数
            if ($tuan_group_item && $tuan_group_item['type']==0 && $tuan_group_item['status']>0 ){
                //判断团长身份
                $friend_order_total = (int)self::getFriendOrderTotal($themeid,$tuan_group_item['uid'],true,$tuan_group_item['pid']);

                if ($friend_order_total){
                    $tuan_gift_info = json_decode($setting['tuan'],true);
                    foreach ($tuan_gift_info as $key => $val){
                        if ($val['key']=='id'){
                            $tuan_gift_id = $val['val'];
                        }
                    }
                    //检查用户是否存在记录
                    $check_tuan_gift = self::checkUserHasGift($themeid,$tuan_gift_id,$tuan_group_item['uid']);

                    if ($check_tuan_gift){
                        //邀请人数的计算  不在同一个团内 计数
//                    $friend_order_total = max(0,($friend_order_total-$config['maxcountall']));

                        //判断是否存在团长礼
                        $order_gift_info = json_decode($setting['order'],true);
                        foreach ($order_gift_info as $key => $val){
                            if ($friend_order_total>=$val['invite']){
                                $order_gift_id = $val['gift_id'];
                                $order_gift = self::getGiftItemById($themeid,$order_gift_id);
                                $check_order_gift = self::checkUserHasGift($themeid,$order_gift_id,$tuan_group_item['uid']);

                                if (!$check_order_gift){
                                    $insert_data = ['order_id'=>$tuan_group_item['id'],'uid'=>$tuan_group_item['uid'],'shangjiaid'=>$order_gift['shangjiaid'],
                                        'gift_id'=>$order_gift_id,'status'=>2,'can_use'=>1,'themeid'=>$themeid
                                    ];
                                    $res = self::insertUserGift($insert_data);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * Desc:团员的处理
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/9 10:11
     */
    public static function tuanMemberOption($themeid,$order_item,$setting,$uid,$order_id)
    {
        if ($setting['send_gift_type']==1){
            // 模式1 支付满团 判断邀请人数
            if ($order_item){

                $fromuid = $order_item['fromuid'];
                //判断邀请人是否是团员
                $from_order_item = Record::getLastGroupByUid($fromuid,$themeid);

                if ($from_order_item && $from_order_item['type']==1 && $order_item['pid']!=$from_order_item['pid'] && $from_order_item['isfinish']==1){

                    $friend_order_total = (int)self::getFriendOrderTotal($themeid,$from_order_item['uid']);

                    if ($friend_order_total){
                        $order_gift_info = json_decode($setting['order'],true);
                        foreach ($order_gift_info as $key => $val){
                            if ($friend_order_total>=$val['invite']){
                                $order_gift_id = $val['gift_id'];
                                $order_gift = self::getGiftItemById($themeid,$order_gift_id);
                                $check_order_gift = self::checkUserHasGift($themeid,$order_gift_id,$from_order_item['uid']);

                                if (!$check_order_gift){
                                    $insert_data = ['order_id'=>$from_order_item['id'],'uid'=>$from_order_item['uid'],'shangjiaid'=>$order_gift['shangjiaid'],
                                        'gift_id'=>$order_gift_id,'status'=>2,'can_use'=>1,'themeid'=>$themeid
                                    ];
                                    $res = self::insertUserGift($insert_data);
                                }
                            }
                        }
                    }
                }
            }
        }
        if ($setting['send_gift_type']==2){
            // 模式2 支付不满团 判断邀请人数
            if ($order_item){

                $fromuid = $order_item['fromuid'];
                //判断邀请人是否是团员
                $from_order_item = Record::getLastGroupByUid($fromuid,$themeid);

                if ($from_order_item && $from_order_item['type']==1 && $from_order_item['status']>0 && $order_item['pid']!=$from_order_item['pid'] ){

                    $friend_order_total = (int)self::getFriendOrderTotal($themeid,$from_order_item['uid']);

                    if ($friend_order_total){
                        $order_gift_info = json_decode($setting['order'],true);
                        foreach ($order_gift_info as $key => $val){
                            if ($friend_order_total>=$val['invite']){
                                $order_gift_id = $val['gift_id'];
                                $order_gift = self::getGiftItemById($themeid,$order_gift_id);
                                $check_order_gift = self::checkUserHasGift($themeid,$order_gift_id,$from_order_item['uid']);

                                if (!$check_order_gift){
                                    $insert_data = ['order_id'=>$from_order_item['id'],'uid'=>$from_order_item['uid'],'shangjiaid'=>$order_gift['shangjiaid'],
                                        'gift_id'=>$order_gift_id,'status'=>2,'can_use'=>1,'themeid'=>$themeid
                                    ];
                                    $res = self::insertUserGift($insert_data);
                                }
                            }
                        }
                    }
                }
            }
        }
        if ($setting['send_gift_type']==3){
            // 模式3 不支付 判断邀请人数
            if ($order_item){
                $fromuid = $order_item['fromuid'];
                if ($fromuid){
                    $friend_order_total = (int)self::getFriendOrderTotal($themeid,$fromuid);
                    if ($friend_order_total){
                        $order_gift_info = json_decode($setting['order'],true);
                        foreach ($order_gift_info as $key => $val){
                            if ($friend_order_total>=$val['invite']){
                                $order_gift_id = $val['gift_id'];
                                $order_gift = self::getGiftItemById($themeid,$order_gift_id);
                                $check_order_gift = self::checkUserHasGift($themeid,$order_gift_id,$fromuid);

                                if (!$check_order_gift){
                                    $insert_data = ['order_id'=>$order_item['id'],'uid'=>$fromuid,'shangjiaid'=>$order_gift['shangjiaid'],
                                        'gift_id'=>$order_gift_id,'status'=>2,'can_use'=>1,'themeid'=>$themeid
                                    ];
                                    $res = self::insertUserGift($insert_data);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public static function randomFloat($min,$max)
    {
        $new_min = $min*100;
        $new_max = $max*100;
        $num = mt_rand($new_min,$new_max)/100;
        return $num;
    }

    /**
     * Desc:红包发放  禁用教培中的红包发放
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/8 9:23 上午
     */
    public static function redPackageOut($themeid,$uid)
    {
        return;
        $fans = db_get(t_fans,['themeid'=>$themeid,'uid'=>$uid]);
        //获取订单
        $themyrecord = Record::getLastGroupByUid($uid,$themeid);
        //判断上级是否是员工
        $myworker = Worker::getThemeWorkerByOpenidNew($themyrecord['fopenid'],$themeid);
        if ($myworker){
            $setting = self::getRewardByWhere(['themeid'=>$themeid]);
            if ($setting && $setting['group_min_out_price']>0 && $setting['group_max_out_price']>0)
            {
                //获取随机金额
                $randomfee = self::randomFloat($setting['group_min_out_price'],$setting['group_max_out_price']);
                //使员工发团长提成
                $ordersn = getMillisecond();
                $data = array(
                    'uniacid' => $themyrecord['uniacid'],
                    'themeid' => $themyrecord['themeid'],
                    'recordid' => $themyrecord['id'],
                    'ordersn' => $ordersn,
                    'type' => 6,//员工提成类型
                    'openid' => $myworker['openid'],
                    'uid' => $myworker['uid'],
                    'addtime' => TIMESTAMP,
                    'fee' => $randomfee,
                    'fopenid' => $themyrecord['openid'],
                    'fromuid' => $themyrecord['uid'],
                    'status' => 0,
                );

                $res = Comm::add($data);
            }
        }else{
            $parent_item = db_get(t_record,['themeid'=>$themeid,'uid'=>$themyrecord['fromuid']]);

            if ($parent_item){
                //当前用户与上级pid是否一致
                if ($parent_item['pid']==$themyrecord['pid']){
                    //查找此团的团长
                    $group_item_order = db_get(t_record,['themeid'=>$themeid,'id'=>$parent_item['pid'],'type'=>0]);

                    if ($group_item_order){
                        //判断团长的推荐人是否是员工
                        $isworker = Worker::getThemeWorkerByOpenidNew($group_item_order['fopenid'],$themeid);
                        if ($isworker){
                            $setting = self::getRewardByWhere(['themeid'=>$themeid]);
                            if ($setting && $setting['min_out_price']>0 && $setting['max_out_price']>0){
                                //团员提成
                                $randomfee = self::randomFloat($setting['min_out_price'],$setting['max_out_price']);
                                $ordersn = getMillisecond();
                                $data = array(
                                    'uniacid' => $themyrecord['uniacid'],
                                    'themeid' => $themyrecord['themeid'],
                                    'recordid' => $themyrecord['id'],
                                    'ordersn' => $ordersn,
                                    'type' => 6,//员工提成类型
                                    'openid' => $isworker['openid'],
                                    'uid' => $isworker['uid'],
                                    'addtime' => TIMESTAMP,
                                    'fee' => $randomfee,
                                    'fopenid' => $themyrecord['openid'],
                                    'fromuid' => $themyrecord['uid'],
                                    'status' => 0,
                                );

                                $res = Comm::add($data);
                            }
                        }
                    }

                }
            }
        }
    }
    //预订单生成
    public static function apiInsertUserInfo($themeid,$recordid,$coupon_id)
    {
        global $_P, $_G;
        $course_address = $_P['course_address'];
        $gift_ids = explode(",",$_P['gift_ids']);
        foreach ($course_address as $key => $val)
        {
            $course_ids .= $val['courseid'].',';
        }
        $order_item = db_get(t_record,['id'=>$recordid,'themeid'=>$themeid]);
        $uid = $order_item['uid'];
        if ($order_item){
            //判断用户是否存在同一订单号的礼品选择记录
            $delete_gift = self::delUserGiftByWhere(['themeid'=>$themeid,'uid'=>$uid]);

            //插入礼品、选择课程
            if ($gift_ids && is_array($gift_ids) && $gift_ids[0]){
                $log_txt = '用户预订单选择礼品:';
                foreach ($gift_ids as $key => $val)
                {
                    $item = self::getGiftItemById($themeid,$val);
                    $data = ['order_id'=>$recordid,'uid'=>$uid,'shangjiaid'=>$item['shangjiaid'],
                        'gift_id'=>$val,'status'=>1,'themeid'=>$themeid];
                    $res = self::insertUserGift($data);
                    $log_txt.= $item['shangjia_name'].'('.$item['name'].');';
                }
                Userdata::addLog($themeid, $_G['member']['uid'], 0,$log_txt);
            }
            //删除用户存在同一订单号的课程选择记录
            $delete_course = self::deleteUserCourseAddressByWhere(['themeid'=>$themeid,'uid'=>$uid]);
            //插入选择课程以及校区
            $log_txt = '用户预订单选择课程:';
            foreach ($course_address as $key => $val)
            {
                $item = self::getCourseItemById($themeid,$val['courseid']);
                $data = [
                    'order_id'=>$recordid,
                    'uid'=>$uid,
                    'shangjiaid'=>$val['shangjia_id'],
                    'course_id'=>$val['courseid'],
                    'address'=>$val['address'],
                    'themeid'=>$themeid
                ];
                $checked_item = self::getUserCourseAddress(['order_id'=>$recordid,'uid'=>$uid,'shangjiaid'=>$val['shangjia_id'],'course_id'=>$val['courseid'],'themeid'=>$themeid]);
                if (!$checked_item){
                    $res = self::insertUserCourseAddress($data);
                    $log_txt.= $item['shangjia_name'].'('.$item['name'].');';
                }else{
                    $log_txt.= '存在重复记录：'.$item['shangjia_name'].'('.$item['name'].');';
                }


            }
            Userdata::addLog($themeid, $_G['member']['uid'], 0,$log_txt);
        }
    }

    /**
     * Desc:插入用户优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/5 8:21 下午
     * @param $data
     * @return mixed
     */
    public static function insertUserCoupon($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_user_coupon,$data);
    }

    /**
     * Desc:更新用户优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 3:29 下午
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function updateUserCoupon($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_user_coupon,$data,$where);
    }

    /**
     * Desc:插入课程校区
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/5 8:38 下午
     * @param $data
     * @return mixed
     */
    public static function insertUserCourseAddress($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_address_user_course,$data);
    }

    /**
     * Desc:删除同一订单号下的课程地址选择记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/6 9:24 下午
     * @param $where
     * @return mixed
     */
    public static function deleteUserCourseAddressByWhere($where)
    {
        return db_delete(t_shangjia_address_user_course,$where);
    }

    public static function deleteUserDobCourseAddressByWhere($ids)
    {
        $sql = " delete from ".tablename(t_shangjia_address_user_course)." where id in ($ids)";
        return db_query($sql);
    }

    public static function deleteUserDobGiftByWhere($ids)
    {
        $sql = " delete from ".tablename(t_shangjia_user_gift)." where id in ($ids)";
        return db_query($sql);
    }

    /**
     * Desc:更新用户课程校区数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 2:26 下午
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function updateUserCourseAddress($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_address_user_course,$data,$where);
    }

    /**
     * Desc:判断用户是否领取过
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/4 7:23 下午
     * @param $themeid
     * @param $uid
     * @param $shangjiaid
     * @param $coupon_id
     */
    public static function userGetCoupon($themeid,$uid,$workerid)
    {
        //判断用户是否存在已使用的优惠券
        $used_coupon_flag = self::getUserCoupon($themeid,$uid,false);
        if ($used_coupon_flag){
            return [];
        }
        //根据workerid查询商家
        $shangjia_item = db_get(t_worker,['uid'=>$workerid,'themeid'=>$themeid]);
        $shangjiaid = $shangjia_item['company'];
        if ($shangjia_item){
            //查询商家独用优惠券
            $shangjia_coupon = db_get(t_shangjia_coupon,['themeid'=>$themeid,'shangjiaid'=>$shangjia_item['company'],'status'=>1]);
            if ($shangjia_coupon){
                $coupon_id = $shangjia_coupon['id'];
            }else{
                //查询商家通用优惠券
                $public_shangjia_coupon = db_get(t_shangjia_coupon,['themeid'=>$themeid,'shangjiaid'=>0,'status'=>1]);
                $coupon_id = $public_shangjia_coupon['id'];
            }
            //判断优惠券id
            if ($coupon_id){
                $data = ['themeid'=>$themeid,'uid'=>$uid,'shangjiaid'=>$shangjia_item['company'],'coupon_id'=>$coupon_id];
                //判断用户是否领取过当前优惠券
                $res = db_get(t_shangjia_user_coupon,$data);
                $item = db_get(t_shangjia_coupon,['id'=>$coupon_id,'themeid'=>$themeid]);
                //判断优惠券是否可用
                $now = date("Y-m-d H:i:s",time());
                if ($item && ($item['get_start_time']<=$now) && ($now<=$item['get_end_time'])){
                    //判断当前优惠券是否可领取
                    if (!$res){
                        $result = $insertid = db_insert(t_shangjia_user_coupon,$data);
                        //更新商家优惠券
                        $new_get_num = $item['get_num']+1;
                        $where = ['themeid'=>$themeid,'shangjiaid'=>$shangjiaid,'id'=>$coupon_id];
                        $update_data = ['get_num'=>$new_get_num];
                        $result1 = self::editCouponItem($where,$update_data);

                        $shangjia_item = db_get(t_shangjia,['id'=>$shangjiaid]);
                        $item['shangjia'] = $shangjia_item['name'];
                        return $item;
                    }else{
                        if ($res['status']==1){
                            $shangjia_item = db_get(t_shangjia,['id'=>$shangjiaid]);
                            $item['shangjia'] = $shangjia_item['name'];
                            return $item;
                        }
                    }
                }
            }
        }
        return [];
    }

    /**
     * Desc:获取用户优惠券信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/4 10:24 下午
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getUserCoupon($themeid,$uid,$is_use = true)
    {
        if (!$is_use){
            return db_get(t_shangjia_user_coupon,['themeid'=>$themeid,'uid'=>$uid,'status'=>1]);
        }
        return db_get(t_shangjia_user_coupon,['themeid'=>$themeid,'uid'=>$uid,'status'=>2]);
    }

    /**
     * Desc:获取用户优惠券记录以及优惠券信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/15 3:27 下午
     * @param $themeid
     * @param $uid
     * @return array
     */
    public static function getUserCouponInfo($themeid,$uid)
    {
        $user_coupon_flag = self::getUserCoupon($themeid,$uid,false);
        if ($user_coupon_flag){
            $now = date("Y-m-d H:i:s",time());
            $coupon_info = db_get(t_shangjia_coupon,['id'=>$user_coupon_flag['coupon_id'],'themeid'=>$themeid]);
            if ($coupon_info && ($coupon_info['use_start_time']<=$now) && ($now<=$coupon_info['use_end_time'])){
                return $coupon_info;
            }else{
                return [];
            }

        }else{
            return [];
        }
    }

    /**
     * Desc:获取查询条件下的商家列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:35 上午
     * @param $where
     * @return mixed
     */
    public  static function getShangjiaList()
    {
        $sql = " select * from ".tablename(t_shangjia)." where id >0 and state=1 order by displayorder";
        return db_select($sql);
    }

    public static function getSjRealSelectedCourseTotal($themeid)
    {
//        self::educationCheck($themeid);
        $all_total = 0;
        $all_arr = [];
        $shangjia_list = self::getShangjiaList();
        foreach ($shangjia_list as $k => $v){
            $temp_arr = [];
            $sql = "SELECT count(*) as real_total FROM ".tablename(t_shangjia_address_user_course)." as a".
                " left join ".tablename(t_record)."as b on a.order_id=b.id and b.themeid='$themeid'".
                " WHERE a.themeid = ". $themeid."  and b.status=1 and a.shangjiaid = " .$v['id'];
            $sj_course_real_total = db_find($sql)['real_total'];
            $temp_arr['id'] = $v['id'];
            $temp_arr['name'] = $v['name'];
            $temp_arr['total'] = $sj_course_real_total;
            $all_total+= $sj_course_real_total;
            array_push($all_arr,$temp_arr);
        }
        array_unshift($all_arr,['id'=>0,'name'=>'全部商家','total'=>$all_total]);
        return $all_arr;
    }

    public static function getShangjiaByPage($page_start=0,$page_size=10)
    {
        $sql = " select * from ".tablename(t_shangjia)." where id >0 and state=1 order by displayorder limit $page_start,$page_size";
        return db_select($sql);
    }

    /**
     * Desc:通过商家id获取商家信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/4/19 15:15
     * @param int $id
     * @return mixed
     */
    public static function getShangjiaItem($id=0)
    {
        return db_get(t_shangjia,['id'=>$id]);
    }

    /**
     * Desc:获取两个位置之间的距离/km
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/27 9:13 下午
     * @param string $point1
     * @param string $point2
     * @return float
     */
    public static function distance($point1='',$point2='')
    {
        if (empty($point1) || empty($point2)){
            return 0;
        }
        $point_arr1 = explode(",",$point1);
        $point_arr2 = explode(",",$point2);
        $radLat1=deg2rad((double)$point_arr1[0]);
        $radLat2=deg2rad((double)$point_arr2[0]);
        $radLng1=deg2rad((double)$point_arr1[1]);
        $radLng2=deg2rad((double)$point_arr2[1]);
        $a=$radLat1-$radLat2;//两纬度之差,纬度<90
        $b=$radLng1-$radLng2;//两经度之差纬度<180
        $s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137;
        return number_format($s,2);
    }

    /**
     * Desc:获取、搜索课程列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 8:46 上午
     * @param $themeid
     * @param $shangjiaid
     * @param $name
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public  static function getCourseList($themeid,$shangjiaid,$name,$page_start=0,$page_size=10,$status=0,$sort='',$key=1,$count = false,$shangjia_category_id=0)
    {
        $condition = "";
        if ($shangjiaid){
            $condition .= " and a.shangjiaid = $shangjiaid";
        }
        if ($shangjia_category_id){
            $condition .= " and a.shangjia_category_id = $shangjia_category_id";
        }
        if ($status){
            $condition .= " and a.status=$status";
        }
        if ($name){
            $condition .= " and a.name like '%".$name."%' or b.name like '%".$name."%' ";
        }
        if ($sort){
            if ($key==1){
                $condition .= " order by  ".$sort." desc";
            }else{
                $condition .= " order by  ".$sort." asc";
            }
        }else{
            $condition .= " order by a.shangjiaid,b.displayorder asc";
        }
        if ($page_size && !$count){
            $condition .= " limit ".$page_start.",".$page_size;
        }
        $sql = "  from ".tablename(t_shangjia_course)." as a".
            " left join ".tablename(t_shangjia)." as b  on a.shangjiaid=b.id ".
            "  where a.themeid=$themeid".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " select a.*,b.name as shangjia_name,b.address,b.mappoint,b.mobile,b.id as shangjia_id,b.shangjia_rule_id ".$sql;
            return db_select($sql);
        }

    }

    public static function getUserCanEditCourseList($themeid,$shangjiaid,$uid)
    {
        $sql1 = ' select group_concat(course_id) as course_ids from '.tablename(t_shangjia_address_user_course).
            " where themeid=$themeid and uid='$uid' ";
        $not_in = db_find($sql1)['course_ids'];
        $condition = '';
        if ($not_in){
            $condition = ' and a.id not in('.$not_in.')';
        }
        $sql = "  from ".tablename(t_shangjia_course)." as a".
            " left join ".tablename(t_shangjia)." as b  on a.shangjiaid=b.id ".
            "  where a.themeid=$themeid and b.id=$shangjiaid ".$condition;
        $sql = " select a.*,b.name as shangjia_name,b.address,b.mappoint,b.mobile,b.id as shangjia_id,b.shangjia_rule_id ".$sql;
        $list =  db_select($sql);
        foreach ($list as $k => $v){
            $list[$k]['address'] = json_decode($v['address'],true);
        }
        return $list;
    }

    public static function getUserCourseTotal($themeid,$record_id,$uid)
    {
        $sql = " select count(*) as cnt from ".tablename(t_shangjia_address_user_course)." where themeid='$themeid' and uid='$uid' and order_id='$record_id'";
        return db_find($sql)['cnt'];
    }
    
    public static function getUserGiftTotal($themeid,$record_id,$uid)
    {
        $sql = " select count(*) as cnt from ".tablename(t_shangjia_user_gift)." where themeid='$themeid' and uid='$uid' and order_id='$record_id'";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取商家课程数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/1 5:24 下午
     * @param $themeid
     * @param $shangjiaid
     * @return mixed
     */
    public static function getCourseTotal($themeid,$shangjiaid,$status=-1)
    {
        $sql = " SELECT COUNT(*) AS cnt FROM ".tablename(t_shangjia_course)." where themeid=$themeid and shangjiaid=$shangjiaid";
        if ($status!=-1){
            $sql.= " and status=$status";
        }
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取指定的课程详情
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 8:50 上午
     * @param $themeid
     * @param $id
     * @return mixed
     */
    public  static function getCourseItemById($themeid,$id)
    {
        $sql = " select a.*,b.name as shangjia_name from ".tablename(t_shangjia_course)." as a".
            " left join ".tablename(t_shangjia)." as b on a.shangjiaid=b.id ".
            " where a.themeid=$themeid and a.id=$id";
        return db_find($sql);
    }

    /**
     * Desc:通过ids查询课程
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/2 3:33 下午
     * @param $themeid
     * @param $ids
     * @return mixed
     */
    public static function getCourseListByIds($themeid,$ids)
    {
        $sql = " select a.*,b.name as shangjia_name from ".tablename(t_shangjia_course)." as a".
            " left join ".tablename(t_shangjia)." as b on a.shangjiaid=b.id ".
            " where a.themeid=$themeid and a.id in (".$ids.") ";
        return db_select($sql);
    }

    /**
     * Desc:修改课程信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 8:54 上午
     * @param $where
     * @param $data
     * @return bool
     */
    public  static function editCourseItem($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_course,$data,$where);
    }

    /**
     * Desc:删除课程
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 8:56 上午
     * @param $where
     * @return mixed
     */
    public  static function delCourseItem($where)
    {
        return db_delete(t_shangjia_course,$where);
    }

    /**
     * Desc:新增商家课程
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:33 上午
     * @param $data
     * @return mixed
     */
    public  static function insertCourse($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_course,$data);
    }

    /**
     * Desc:新建机构信息记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/2 6:50 下午
     * @param $data
     * @return mixed
     */
    public static function insertCompanyInfo($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_company_info,$data);
    }

    /**
     * Desc:获取用户机构信息填写
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/2 6:51 下午
     * @param $where
     * @return mixed
     */
    public static function getCompanyInfoByWhere($where)
    {
        return db_get(t_shangjia_company_info,$where);
    }

    /**
     * Desc:获取商家预留信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/14 1:59 下午
     * @param $themeid
     * @param int $page_start
     * @param int $page_size
     * @param string $start_day
     * @param string $end_day
     * @param string $search
     * @return mixed
     */
    public static function getCompanyInfoList($themeid,$page_start=0,$page_size=10,$start_day='',$end_day='',$search='',$type,$count = false)
    {
        $condition="";
        if ($search){
            $condition .= " AND mobile LIKE '".$search."'"." or username LIKE '".$search."'"." or company_name LIKE '".$search."'"." or address LIKE '".$search."'";
        }
        if ($start_day && $end_day && $start_day!=$end_day){
            $condition .= "  and created_at between '".$start_day."' and '".$end_day."'";
        }
        if ($type){
            $condition .= "  and type=".$type;
        }

        $condition .= " ORDER BY created_at DESC ";


        if ($page_size && !$count) {
            $condition.= "LIMIT ".$page_start.",".$page_size;
        }
        $sql = " FROM "
            .tablename(t_shangjia_company_info).
            " WHERE themeid=$themeid ".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " SELECT * ".$sql;
            return db_select($sql);
        }

    }

    /**
     * Desc:获取商户预留合作信息格式化数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/14 2:33 下午
     * @param $themeid
     * @return array[]
     */
    public static function getCompanyTypeCount($themeid)
    {
        $type_list = [
            ['title'=>'全部','type'=>0],
            ['title'=>'机构','type'=>1],
            ['title'=>'城市服务商','type'=>2]
        ];
        foreach ($type_list as $key =>$val){
            $type = $val['type'];
            if ($type==0){
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_company_info)." where  themeid=".$themeid;
            }else{
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_company_info)." where type=$type and themeid=".$themeid;
            }
            $type_list[$key]['total'] =  intval(db_find($sql)['cnt']);
        }
        return $type_list;
    }

    /**
     * Desc:获取最近20条订单
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/2 8:05 下午
     * @param $themeid
     * @return mixed
     */
    public static function getOrderList($themeid)
    {
        $sql = "SELECT username,avatar,mobile,addtime,fee FROM ".tablename(t_record)."
                        WHERE themeid =$themeid and status > 0 or status=-2  order by id desc limit 20";
        return db_select($sql);
    }

    /**
     * Desc:获取虚拟的用户订单数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/29 14:28
     * @param $config
     * @param int $limit
     * @return mixed
     */
    public static function getVirtualOrderList($config,$limit=50)
    {
        $cache_key = MODULE_NAME.'_edu_order';
        $cache_time_key = 'edu_time';
        if (strstr($config['softtag0'],"婚纱")!==false ){
            $kaishishu = intval( substr(MODULE_NAME, -1))%7*30+730+3*date('H');
        }else{
            $kaishishu = intval( substr(MODULE_NAME, -1))%10*40+10*date('H');
        }
        if (cache_load($cache_key)){
            $kaishishu = cache_load($cache_key);
        }else{
            cache_write($cache_key, $kaishishu);
            cache_write($cache_time_key, date("Y-m-d",time()));
        }
        if ($kaishishu>4200){
            $kaishishu =1;
            cache_write($cache_key, $kaishishu);
        }
        $xunisql = "SELECT id,username,avatar,mobile FROM " . tablename(t_2019fans) .
            " WHERE id >". $kaishishu ." and avatar!=''  LIMIT $limit";
        $res = db_select($xunisql);

        if ($res){
            $last_item = end($res);
            if (cache_load($cache_key) != date("Y-m-d",time()) && $last_item){
                cache_write($cache_key, $last_item['id']);
            }
            foreach ($res as $k => $v){
                //取昵称中的第一位根据ascii码算得秒数
                $nickname = mb_substr($v['username'],0,1,'utf-8');
                $nickname = mb_convert_encoding($nickname, 'GBK');
                if ($nickname){
                    $miao = ord($nickname) % 60;

                    //取昵称中的第一位根据ascii码算得分钟数
                    $nickname = mb_substr($v['username'],1,1,'utf-8');
                    $nickname = mb_convert_encoding($nickname, 'GBK');
                    $fen = ord($nickname) % 60;

                    //取当前时间计算小时数
                    $xiaoshi = date('H')-7;
                    if ($xiaoshi<0){
                        $created_at=date("Y-m-d",'-1 day');
                        $xiaoshi = 12;
                    }else{
                        $created_at=date("Y-m-d");
                    }
                    if($xiaoshi==0){
                        $xiaoshi = 12;
                    }
                    $xiaoshi = $xiaoshi==0?7:ord($nickname) % $xiaoshi + 7;
                    if ($xiaoshi<10){ $xiaoshi = "0".$xiaoshi;}
                    if ($fen<10){ $fen = "0".$fen;}
                    if ($miao<10){ $miao = "0".$miao;}
                    $created_at = $created_at ." " .$xiaoshi .":".$fen.":".$miao;
                    $res[$k]['addtime'] = strtotime($created_at);
                    $res[$k]['fee'] = self::randPrice($config);
                    unset($res[$k]['id']);
                }
            }
        }
        return $res;
    }

    /**
     * Desc:返回格式化后的真实+虚拟订单
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/29 14:26
     * @param $themeid
     * @param $config
     * @param int $limit
     * @return array
     */
    public static function getFormatOrderList($themeid,$config,$limit=50)
    {
        $real = self::getOrderList($themeid);

        if ($config['fakejoin']>0){
            $fakejoin = (int)$config['fakejoin'];
            if ($fakejoin<$limit){
                $limit = $fakejoin;
            }
            $virtual = self::getVirtualOrderList($config,$limit);
            $total_arr = array_merge($real,$virtual);
            $sort = array_column($total_arr, 'addtime');
            array_multisort($sort, SORT_DESC, $total_arr);
        }else{
            $total_arr = $real;
        }

        return $total_arr;
    }


    public static function getFormatGiftList($themeid,$config,$limit=50)
    {
        $item = self::getRewardByWhere(['themeid'=>$themeid]);
        $other_config = json_decode($item['other_config'],true);
        $open_tuan_other_name = $other_config['open_tuan_other_name'];
        $format_user_flag_list = [];
        $real_list = self::getUserGift($themeid,0,'',0,50);
        foreach ($real_list as $kk => $vv){
            $temp_arr = [
                'avatar'=>$vv['avatar']?$vv['avatar']:'https://css2020.yixuan.net/2020css/yx2020/images/question.png',
                'nickanme'=>$vv['username']?$vv['username']:$vv['nickname'],
                'txt'=>'解锁价值'.$vv['price'].'元'.$vv['name'],
                'status_txt'=>$open_tuan_other_name,
                'time'=>date("Y-m-d",strtotime($vv['created_at']))
            ];
            array_push($format_user_flag_list,$temp_arr);
        }
        //获取礼品
        $gifts = self::getGiftList($themeid,0,'',0,20,'',1);
        if ($gifts){
            $total = count($gifts);
            if ($config['fakejoin']>0){
                $virtual = self::getVirtualOrderList($config,$limit);
                if ($virtual){
                    foreach ($virtual as $k => $v){
                        $tmp_rand_key = rand(0,($total-1));
                        $gift_item = $gifts[$tmp_rand_key];
                        $temp_arr = [
                            'avatar'=>$v['avatar'],
                            'nickanme'=>$v['username'],
                            'txt'=>'解锁价值'.$gift_item['price'].'元'.$gift_item['name'],
                            'status_txt'=>$open_tuan_other_name,
                            'time'=>date("Y-m-d",$v['addtime'])
                        ];
                        array_push($format_user_flag_list,$temp_arr);
                    }
                }
            }
            $sort = array_column($format_user_flag_list, 'time');
            array_multisort($sort, SORT_DESC, $format_user_flag_list);
        }
        return $format_user_flag_list;
    }

    /**
     * Desc:获取随机的价格
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/29 14:23
     * @param $config
     * @return array|int|string
     */
    public static function randPrice($config)
    {
        $groupprice = $config['groupprice'];
        $primeprice = $config['primeprice'];
        $joinfee = $config['joinfee'];
        $tmp_arr = [];
        if ($groupprice!='0.00'){
            array_push($tmp_arr,$groupprice);
        }
        if ($primeprice!='0.00'){
            array_push($tmp_arr,$primeprice);
        }
        if ($joinfee!='0.00'){
            array_push($tmp_arr,$joinfee);
        }
        $rand_key = array_rand($tmp_arr,1);
        return $tmp_arr[$rand_key];
    }

    /**
     * Desc:获取、搜索商家礼品类表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:32 上午
     * @param $themeid
     * @param $shangjiaid
     * @param $name
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public  static function getGiftList($themeid,$shangjiaid=0,$name='',$page_start=0,$page_size=10,$type='',$status=-1,$count = false)
    {
        $condition = "";
        if ($shangjiaid){
            $condition .= " and a.shangjiaid = $shangjiaid";
        }
        if (is_numeric($type)){
            $condition .= " and a.type = $type";
        }
        if ($status>-1){
            $condition .= " and a.status = $status";
        }
        if ($name){
            $condition .= " and a.name like '%".$name."%' or b.name like '%".$name."%' ";
        }
        $condition .= " order by a.sort ";
        if ($page_size && !$count){
            $condition .= " limit ".$page_start.",".$page_size;
        }
        $sql = "  from ".tablename(t_shangjia_gift)." as a".
            " left join ".tablename(t_shangjia)." as b  on a.shangjiaid=b.id ".
            " where a.themeid=$themeid".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " select a.*,b.name as shangjia_name ".$sql;
            return db_select($sql);
        }

    }

    /**
     * Desc:获取用户的课程选择记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/6 10:59
     * @param $where
     * @return mixed
     */
    public static function getUserCourseAddress($where)
    {
        return db_get(t_shangjia_address_user_course,$where);
    }

    /**
     * Desc:修改用户课程选择记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/6 11:22
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function editUserCourseAddress($where,$data)
    {
        return db_update(t_shangjia_address_user_course,$data,$where);
    }



    /**
     * Desc:获取用户礼品记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 11:12 上午
     * @param $themeid
     * @param string $search
     * @param int $page_start
     * @param int $page_size
     * @param string $start_day
     * @param string $end_day
     * @param int $gift_type
     * @return mixed
     */
    public static function getUserGift($themeid,$shangjiaid=0,$search='',$page_start=0,$page_size=10,$start_day='',$end_day='',$gift_type=1,$gift_id=0,$status=0,$recordid=0,$count = false,$uid=0)
    {
        $condition="";
        if ($shangjiaid){
            $condition .= " and a.shangjiaid=$shangjiaid ";
        }
        if ($search){
            $condition .= " AND b.nickname LIKE '".$search."'"." or b.mobile LIKE '".$search."' "." or b.username LIKE '".$search."'";
        }
        if ($gift_id){
            $condition .= " and a.gift_id=$gift_id ";
        }
        if ($uid){
            $condition .= " and a.uid=$uid ";
        }else{
            if ($recordid){
                $condition .= " and a.order_id=$recordid ";
            }
        }
        if ($status){
            $condition .= " and a.status=$status ";
        }
        if ($start_day && $end_day && $start_day!=$end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }
        if ($gift_type){
            $condition .= " and a.status=$gift_type";
        }
        $condition .= " ORDER BY a.id DESC ";

        if ($page_size && !$count) {
            $condition.= " LIMIT ".$page_start.",".$page_size;
        }
        $sql = "  FROM ".tablename(t_shangjia_user_gift)." AS  a ".
            " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
            " LEFT JOIN ".tablename(t_shangjia_gift)." AS c ON a.gift_id=c.id and c.themeid=$themeid".
            " LEFT JOIN ".tablename(t_shangjia)." AS d ON a.shangjiaid=d.id ".
            " LEFT JOIN ".tablename(t_record)." AS e ON  e.themeid=$themeid and e.id=a.order_id".
            " WHERE a.themeid=$themeid and a.can_use=1 and e.status=1".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql.$condition));
        }else{
            $sql = " SELECT a.id,a.uid,a.gift_id,a.status,a.created_at,a.updated_at,a.shangjiaid,a.workerid,b.avatar,b.nickname,b.username,b.mobile,c.name,c.top_img,c.price,d.name as shangjainame ".$sql;
            return db_select($sql);
        }


    }

    //格式化订单导出中的礼品获取 名称-商家
    public static function formatUserGift($themeid,$recordid)
    {
        $tmp_str = "";
        $user_flag = self::getUserGift($themeid,0,'',0,0,'','',0,0,0,$recordid);
        foreach ($user_flag as $k => $v){
            $tmp_str .= $v['name'].'-'.$v['shangjainame'].';';
        }
        return $tmp_str;
    }
    /**
     * Desc:获取商家优惠券以及数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/7 9:50 上午
     * @param $themeid
     * @return array[]
     */
    public static function getCouponFromCount($themeid)
    {

        $type_list = [
            ['title'=>'全部','shangjiaid'=>0,'total'=>0]
        ];
        $shangjia = self::getShangjiaList();
        foreach ($shangjia as $key => $val){
            $temp = ['title'=>$val['name'],'total'=>0,'shangjiaid'=>$val['id']];
            array_push($type_list,$temp);
        }
        foreach ($type_list as $key => $val){
            if ($val['title']=='全部'){
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_user_coupon)." where  themeid=".$themeid;
                $type_list[$key]['total'] = intval(db_find($sql)['cnt']);
            }else{
                $shangjia_id = $val['shangjiaid'];
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_user_coupon)." where shangjiaid=$shangjia_id and  themeid=".$themeid;
                $type_list[$key]['total'] = intval(db_find($sql)['cnt']);
            }
        }
        return $type_list;
    }

    /**
     * Desc:获取礼品类型数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 11:27 上午
     * @param $themeid
     * @return array[]
     */
    public static function getFlagTypeCount($themeid)
    {
        $type_list = [
            ['title'=>'全部','status'=>0],
            ['title'=>'赠品','status'=>1],
            ['title'=>'礼品','status'=>2]
        ];
        foreach ($type_list as $key =>$val){
            $status = $val['status'];
            if ($status==0){
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_user_gift)." where  themeid=".$themeid." and can_use=1";
            }else{
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_user_gift)." where status=$status and themeid=".$themeid." and can_use=1";
            }
            $type_list[$key]['total'] =  intval(db_find($sql)['cnt']);
        }
        return $type_list;
    }

    /**
     * Desc:获取记录中的用户获取数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 11:40 上午
     * @param $themeid
     * @return array[]
     */
    public static function getGiftFlagCount($themeid)
    {
        $prize_list = [
            ['title'=>'全部','total'=>0,'gift_id'=>0]
        ];
        $res = self::getGiftList($themeid);
//        $sort = array_column($res, 'show_pr');
//        array_multisort($sort, SORT_ASC, $res);
        foreach ($res as $key => $val){
            $temp = ['title'=>$val['name'],'total'=>0,'gift_id'=>$val['id']];
            array_push($prize_list,$temp);
        }
        foreach ($prize_list as $key => $val){
            if ($val['title']=='全部'){
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_user_gift)." where  themeid=".$themeid." and can_use=1";
                $prize_list[$key]['total'] = intval(db_find($sql)['cnt']);
            }else{
                $gift_id = $val['gift_id'];
                $sql = "select count(*) as cnt from " . tablename(t_shangjia_user_gift)." where gift_id=$gift_id and  themeid=".$themeid." and can_use=1";
                $prize_list[$key]['total'] = intval(db_find($sql)['cnt']);
            }
        }
        return $prize_list;
    }

    /**
     * Desc:获取商家礼品
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:32 上午
     * @param $themeid
     * @param $id
     * @return mixed
     */
    public  static function getGiftItemById($themeid,$id)
    {
        $sql = " select a.*,b.name as shangjia_name from ".tablename(t_shangjia_gift)." as a ".
            "left join ".tablename(t_shangjia)." as b on a.shangjiaid=b.id ".
            " where a.themeid=$themeid and a.id=$id";
        return db_find($sql);
    }

    /**
     * Desc:修改商家礼品
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:32 上午
     * @param $where
     * @param $data
     * @return mixed
     */
    public  static function editGiftItem($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_gift,$data,$where);
    }

    /**
     * Desc:删除商家礼品
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:31 上午
     * @param $where
     * @return mixed
     */
    public  static function delGiftItem($where)
    {
        return db_delete(t_shangjia_gift,$where);
    }

    /**
     * Desc:新增商家礼品
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:31 上午
     * @param $data
     * @return mixed
     */
    public  static function insertGift($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_gift,$data);
    }

    /**
     * Desc:获取、搜索商家优惠券的列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:31 上午
     * @param $themeid
     * @param $shangjiaid
     * @param $name
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public  static function getCouponList($themeid,$shangjiaid,$name,$page_start=0,$page_size=10)
    {
        $condition = "";
        if ($shangjiaid){
            $condition .= " and a.shangjiaid = $shangjiaid";
        }
        if ($name){
            $condition .= " and a.name like '%".$name."%' or b.name like '%".$name."%' ";
        }
        if ($page_size){
            $condition .= " limit ".$page_start.",".$page_size;
        }
        $sql = " select a.*,b.name as shangjia_name from ".tablename(t_shangjia_coupon)." as a ".
            " left join ".tablename(t_shangjia)." as b  on a.shangjiaid=b.id ".
            " where a.themeid=$themeid".$condition;
        return db_select($sql);
    }

    /**
     * Desc:获取用户优惠券记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/6 11:12 上午
     * @param $themeid
     * @param string $search
     * @param int $page_start
     * @param int $page_size
     * @param string $start_day
     * @param string $end_day
     * @param int $gift_type
     * @return mixed
     */
    public static function getUserCouponFlag($themeid,$shangjiaid=0,$search='',$page_start=0,$page_size=10,$start_day='',$end_day='',$recordid=0,$count = false,$c_id=0,$status=0)
    {
        $condition="";
        if ($c_id){
            $condition .= " and a.coupon_id=$c_id ";
        }
        if ($status){
            $condition .= " and a.status=$status ";
        }
        if ($shangjiaid){
            $condition .= " and a.shangjiaid=$shangjiaid ";
        }
        if ($recordid){
            $condition .= " and a.order_id=$recordid ";
        }
        if ($search){
            $condition .= " AND b.nickname LIKE '".$search."'"." or b.mobile LIKE '".$search."' "." or b.username LIKE '".$search."'";
        }
        if ($start_day && $end_day && $start_day!=$end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }

        $condition .= " ORDER BY a.created_at DESC ";

        if ($page_size && !$count) {
            $condition.= "LIMIT ".$page_start.",".$page_size;
        }
        $sql = "  FROM ".tablename(t_shangjia_user_coupon)." AS  a ".
            " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
            " LEFT JOIN ".tablename(t_shangjia_coupon)." AS c ON a.coupon_id=c.id and c.themeid=$themeid".
            " LEFT JOIN ".tablename(t_shangjia)." AS d ON a.shangjiaid=d.id ".
            " LEFT JOIN ".tablename(t_record)." AS e ON a.order_id=e.id and  e.themeid=$themeid".
            " WHERE a.themeid=$themeid ".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " SELECT a.status,a.created_at,a.updated_at,a.shangjiaid,b.avatar,b.nickname,b.username,b.mobile,c.name,c.price,d.name as shangjainame ".$sql;
            return db_select($sql);
        }

    }

    //格式化订单中 优惠券的使用
    public static function formatUserCouponFlag($themeid,$recordid)
    {
        $msg = '';
        $coupon = self::getUserCouponFlag($themeid,0,'',0,1,'','',$recordid);
        if ($coupon && $coupon[0]){
            $item = $coupon[0];
            if ($item['status']==1){
                $msg.= $item['name'].'-'.'已使用';
            }else{
                $msg.= $item['name'].'-'.'未使用';
            }
        }
        return $msg;
    }

//    课程补录相关操作

    /**
     * Desc:通过相关查询获取订单信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/9/16 08:46
     * @param $themeid
     * @param $search
     * @return mixed
     */
    public static function searchOrderInfo($themeid,$search)
    {
        $condition="";
        if ($search){
            $condition .= " AND nickname LIKE '".$search."'"." or mobile LIKE '".$search."' "." or username LIKE '".$search."'";
        }
        $sql = " select nickname,username,mobile,avatar from ".tablename(t_record)." where themeid=$themeid and (status=1 or status=3) ".$condition;
        $res = db_find($sql);
        return $res;
    }


    public static function getUserCourseFlag($themeid,$shangjiaid=0,$search='',$page_start=0,$page_size=10,$start_day='',$end_day='',$recordid=0,$sort=1,$p_id= 0,$count = false)
    {
        $condition="";
        if ($shangjiaid){
            $condition .= " and a.shangjiaid=$shangjiaid ";
        }
        if ($p_id){
            $condition .= " and a.course_id=$p_id ";
        }
        if ($search){
            $condition .= " AND b.nickname LIKE '".$search."'"." or b.mobile LIKE '".$search."' "." or b.username LIKE '".$search."'";
        }
        if ($start_day && $end_day && $start_day!=$end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }
        if ($recordid){
            $condition .= " and a.order_id=$recordid ";
        }
        if ($sort==1){
            $condition .= " ORDER BY a.created_at DESC ";
        }else{
            $condition .= " ORDER BY a.updated_at DESC ";
        }


        if ($page_size && !$count) {
            $condition.= "LIMIT ".$page_start.",".$page_size;
        }
        $sql = "  FROM "
            .tablename(t_shangjia_address_user_course)." AS  a ".
            " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
            " LEFT JOIN ".tablename(t_shangjia_course)." AS c ON a.course_id=c.id and c.themeid=$themeid".
            " LEFT JOIN ".tablename(t_shangjia)." AS d ON a.shangjiaid=d.id ".
            " LEFT JOIN ".tablename(t_record)." AS e ON a.order_id=e.id and  e.themeid=$themeid".
            " LEFT JOIN ".tablename(t_worker)." AS f ON e.workerid=f.uid and f.themeid=$themeid".
            " WHERE a.themeid=$themeid and e.status=1 ".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " SELECT a.id,a.uid,a.shangjiaid,a.address,a.status,a.created_at,a.updated_at,a.workerid,b.avatar,b.nickname,b.username,b.mobile,c.name,
            c.top_img,d.name as shangjianame,e.fee,e.mobile as order_mobile,f.username as workenname,e.datetime,e.address as raddress,e.formtwo,e.addinfo,e.option ".
                $sql;
            return db_select($sql);
        }

    }

    //格式化订单中导出的课程-校区-商家选择记录
    public static function formatUserCourseFlag($themeid,$recordid=0)
    {
        $user_flag_arr = '';
        $user_flag  = self::getUserCourseFlag($themeid,0,'',0,0,'','',$recordid);
        foreach ($user_flag as $k => $v){
            $user_flag_arr .= $v['name'].'-'.$v['address'].'-'.$v['shangjianame'].';';
        }
        return $user_flag_arr;
    }

    /**
     * Desc:获取指定的优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/16 3:55 下午
     * @param $themeid
     * @param $id
     * @return mixed
     */
    public static function getCoupon($themeid,$id)
    {
        $sql = " select a.*,b.name as shangjia_name from ".tablename(t_shangjia_coupon)." as a ".
            " left join ".tablename(t_shangjia)." as b  on a.shangjiaid=b.id ".
            " where a.themeid=$themeid and a.id=$id";
        return db_find($sql);
    }

    /**
     * Desc:获取最早一条记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/8 3:27 下午
     * @param $themeid
     * @return mixed
     */
    public static function getFirstCoupon($themeid)
    {
        $sql = " select a.*,b.name as shangjia_name from ".tablename(t_shangjia_coupon)." as a ".
            " left join ".tablename(t_shangjia)." as b  on a.shangjiaid=b.id ".
            " where a.themeid=$themeid order by a.id asc limit 1 ";
        return db_find($sql);
    }
    /**
     * Desc:修改商家优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:31 上午
     * @param $where
     * @param $data
     * @return mixed
     */
    public  static function editCouponItem($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_coupon,$data,$where);
    }

    /**
     * Desc:删除商家优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:30 上午
     * @param $where
     * @return mixed
     */
    public  static function delCouponItem($where)
    {
        return db_delete(t_shangjia_coupon,$where);
    }

    /**
     * Desc:新增商家优惠券
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:30 上午
     * @param $data
     * @return mixed
     */
    public  static function insertCoupon($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_coupon,$data);
    }

    /**
     * Desc:获取奖励详情获取指定类型下的奖励列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:29 上午
     * @param $where
     * @param false $is_list
     * @return mixed
     */
    public  static function getRewardByWhere($where,$is_list=false)
    {
        if ($is_list){
            return db_getall(t_shangjia_setting,$where);
        }else{
            return db_get(t_shangjia_setting,$where);
        }
    }

    /**
     * Desc:修改奖励
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:29 上午
     * @param $where
     * @param $data
     * @return mixed
     */
    public  static function editReward($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_setting,$data,$where);
    }

    /**
     * Desc:新增奖励
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:28 上午
     * @return mixed
     */
    public  static function insertReward($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_setting,$data);
    }

    public static function GetShangJiaByLg()
    {
        $shangjia_list = self::getShangjiaList();
        foreach ($shangjia_list as $sk => $sv){
            $shangjia_list[$sk]['address'] = json_decode($sv['address'],true);
            $shangjia_list[$sk]['mappoint'] = json_decode($sv['mappoint'],true);
        }
        $res = [];

    }

    public static function Mine($themeid,$system,$config,$fans,$themyrecord)
    {
        global $_P, $_G, $_S;
        $_S = self::getSystem();
        $item = self::getRewardByWhere(['themeid'=>$themeid]);
        $item['tuan'] = json_decode($item['tuan'],true);
        $item['order'] = json_decode($item['order'],true);
//      获取视频显示位置
        $djs_show = $item['djs_show'];
        $activity_show = $item['activity_show'];
        $flag_show = $item['flag_show'];
        $company_show = $item['company_show'];
        $float_icon_show = $item['float_icon_show'];
        $poster_show = $item['poster_show'];

        
        $poster = Poster::getByThemeIdnew($themeid);
        if(!empty($poster['bg'])){
            $config['isposter']=1;
            if ($fans['status']==2 && $system['s']['istubiao']==1) {
                $config['isposter']=0;
            }
            $pm = ['themeid'=>$themeid,'openid'=>$fans['openid']];
            $myposter = db_find("SELECT * FROM ".tablename(t_fans)."
         WHERE themeid = :themeid and openid = :openid",$pm);
            if (empty($myposter['poster'])){
                $waittips = empty($poster['waittips'])?'正在生成海报':$poster['waittips'];
            }else{
                $waittips='';
            }
            //获取海报的url地址
            $posterurl = "/" . createMobileUrl("poster",array("themeid"=>$themeid,"op"=>"action","fromuid"=>$_P['fromuid'],"fopenid"=>$_P['fopenid'],"recordid"=>intval($themyrecord['id'])));
        }else{
            $waittips='海报未开启';
        }
        $myworker = Worker::getThemeWorkerByOpenid($_G['openid'],$themeid);
        $company_info = [];
        if ($myworker['company']){
            $company_info = self::getShangjiaItem($myworker['company']);
        }

        $pn_wxapp = $_S['pn_wxapp'];
        if (!$pn_wxapp || $pn_wxapp==0){
            //        能否分享
            $canshare = 1;
//       成功购买后生成
            if ($poster_show==2 && !$myworker && !$themyrecord){
                $waittips = '成功购买课程后，才能生成海报';
                $posterurl = '';
                $canshare = 0;
            }
        }else{
            if ($pn_wxapp==1){
                $canshare = 0;
            }elseif ($pn_wxapp==2){
                $canshare = 1;
            }elseif ($pn_wxapp==3){
                //        能否分享
                $canshare = 1;
                //       成功购买后生成
                if (!$myworker && !$themyrecord){
                    $waittips = '成功购买课程后，才能生成海报';
                    $posterurl = '';
                    $canshare = 0;
                }
            }
        }
        //邀请信息
        $invite_info = [];
        //分享
        $user_share_num = $fans['responsum'];
        //排除 自己团成员记录
        if ($themyrecord && $themyrecord['pid']){
            $tuijian_list = db_select("SELECT * FROM ".tablename(t_record)."
	                            WHERE  themeid =" . $themeid ." and status > 0 and pid !='".$themyrecord['pid']."' and fromuid = " .$_G['member']['uid'] ." order by id desc");
        }else{
            $tuijian_list = db_select("SELECT * FROM ".tablename(t_record)."
	                            WHERE  themeid =" . $themeid ." and status > 0  and fromuid = " .$_G['member']['uid'] ." order by id desc");
        }

        //邀请人数
        $user_tuijian_num = count($tuijian_list);
        $poster_info = ['tips'=>$waittips,'img_url'=>$posterurl];
        //底部图
        $setting = self::getRewardByWhere(['themeid'=>$themeid]);
        //总提现金额
        $pm = array(":themeid"=>$themeid,":openid"=>$_G['openid']);
        $totalsuccess = db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename (t_comm) . ' as m 
                WHERE m.themeid = :themeid and (status=1 or status=98 and type=99) and m.openid = :openid',$pm);
        $commssum = Comm::getcommssum($system, $themeid, $config['iscommshowfail']);
        $setting = self::getRewardByWhere(['themeid'=>$themeid]);
        $other_config = json_decode($setting['other_config'],true);
        $school_other_name = $other_config['school_other_name'];
        $course_other_name = $other_config['course_other_name'];
        $gift_other_name = $other_config['gift_other_name'];
        return [
            'commssum'=>$commssum,
            'totalsuccess'=>$totalsuccess,
            'user_share_num'=>$user_share_num,
            'user_tuijian_num'=>$user_tuijian_num,
            'tuijian_list'=>$tuijian_list,
            'poster_info'=>$poster_info,
            'canshare'=>$canshare,
            'school_other_name'=>$school_other_name,
            'course_other_name'=>$course_other_name,
            'gift_other_name'=>$gift_other_name,
        ];
    }

    public static function PayConfirm($themeid,$theme,$system,$config,$fans,$joinid)
    {
        global $_P, $_G;
        if ($_G['ispost']){
            $course_address = $_P['course_address'];
            $gift_ids = explode(",",$_P['gift_ids']);
            foreach ($course_address as $key => $val)
            {
                $course_ids .= $val['courseid'].',';
            }
            $course_ids = rtrim($course_ids,',');

            $checked_course_list = self::getCourseListByIds($themeid,$course_ids);

            //插入礼品、选择课程

            $format_data = [
                'checked_course_list'=>$checked_course_list
            ];
            return $format_data;
        }else{
            $form = [
                ['title'=>$config['nametext'],'type'=>'txt','name'=>'nametext','val'=>'','placeholder'=>'请输入'.$config['nametext']],
                ['title'=>$config['mobiletext'],'type'=>'txt','name'=>'mobiletext','val'=>'','placeholder'=>'请输入'.$config['mobiletext']],
            ];
            if ($config['formtwo']){
                $type = 'txt';
                switch ($config['formtwotype']){
                    case '1':
                        $type = 'number';
                        break;
                    case '6':
                        $type = 'mobile';
                        break;
                    case '7':
                        $type = 'date';
                        break;
                    case '2':
                        $type = 'select';
                        break;
                    case '3':
                        $type = 'radio';
                        break;
                    default:
                        break;
                }
                $temp_arr = ['title'=>$config['formtwo'],'type'=>$type,'name'=>'formtwo','val'=>$config['formtwooptions'],'placeholder'=>'请输入'.$config['formtwo']];
                array_push($form,$temp_arr);
            }
            if ($config['datetime']){
                $type = 'txt';
                switch ($config['datetimetype']){
                    case '2':
                        $type = 'number';
                        break;
                    case '6':
                        $type = 'mobile';
                        break;
                    case '0':
                        $type = 'date';
                        break;
                    default:
                        break;
                }
                $temp_arr = ['title'=>$config['datetime'],'type'=>$type,'name'=>'datetime','val'=>'','placeholder'=>'请输入'.$config['datetime']];
                array_push($form,$temp_arr);
            }
            if ($config['address']){
                $type = 'txt';
                switch ($config['addresstype']){
                    case '1':
                        $type = 'number';
                        break;
                    case '6':
                        $type = 'mobile';
                        break;
                    case '7':
                        $type = 'date';
                        break;
                    case '2':
                        $type = 'select';
                        break;
                    case '3':
                        $type = 'radio';
                        break;
                    default:
                        break;
                }
                $temp_arr = ['title'=>$config['address'],'type'=>$type,'name'=>'address','val'=>$config['addressoptions'],'placeholder'=>'请输入'.$config['address']];
                array_push($form,$temp_arr);
            }
            if ($config['addinfo']){
                $type = 'txt';
                switch ($config['addinfotype']){
                    case '2':
                        $type = 'number';
                        break;
                    case '6':
                        $type = 'mobile';
                        break;
                    case '0':
                        $type = 'date';
                        break;
                    default:
                        break;
                }
                $temp_arr = ['title'=>$config['addinfo'],'type'=>$type,'name'=>'addinfo','val'=>'','placeholder'=>'请输入'.$config['addinfo']];
                array_push($form,$temp_arr);
            }
            if ($config['shops']){
                $type = 'txt';
                $val = '';
                switch ($config['shopstype']){
                    case '2':
                        $type = 'number';
                        break;
                    case '6':
                        $type = 'mobile';
                        break;
                    case '7':
                        $type = 'date';
                        break;
                    case '0':
                        $type = 'select';
                        $range_val = $config['options'];
                        if (!$config['gudingoptions']){
                            $val = $range_val;
                        }else{
                            $guding_val = $config['gudingoptions'];
                            $val = array_merge($guding_val,$range_val);
                            $limit_config = ['min'=>$config['shopsmin'],'max'=>$config['shopsmax']];
                        }
                        break;
                    case '3':
                        $type = 'radio';
                        $val = $config['options'];
                        break;
                    case '4':
                        $type = 'checkbox';
                        $range_val = $config['options'];
                        if (!$config['gudingoptions']){
                            $val = $range_val;
                        }else{
                            $guding_val = $config['gudingoptions'];
                            $val = array_merge($guding_val,$range_val);
                            $limit_config = ['min'=>$config['shopsmin'],'max'=>$config['shopsmax']];
                        }
                        break;
                    case '5':
                        $type = 'shop_checkbox';
                        break;
                    default:
                        break;
                }
                $temp_arr = ['title'=>$config['shops'],'type'=>$type,'name'=>'shops','val'=>$val,'placeholder'=>'请输入'.$config['shops']];
                array_push($form,$temp_arr);
            }
            //获取用户优惠券
//            $myworker = Worker::getThemeWorkerByOpenid($_G['openid'],$themeid,1);
//            var_dump($myworker);die();
            $coupon_item = self::getUserCouponInfo($themeid,$fans['uid']);
            $theme_status = self::checkThemeStatus($theme);


            if ($joinid==9){
                $price = $old_price = $config['primeprice'];
                if ($coupon_item){
                    if ((float)$coupon_item['price']<(float)$old_price){
                        $price = ($old_price-$coupon_item['price']);
                    }else{
                        $coupon_item['price'] = '';
                    }
                    $price_info = ['now_price'=>$price,'coupon'=>$coupon_item['price']];
                }else{
                    $price_info = ['now_price'=>$price,'coupon'=>''];
                }
            }else{
                $price = $old_price = $config['groupprice'];
                if ($coupon_item){
                    if ((float)$coupon_item['price']<(float)$old_price){
                        $price = ($old_price-$coupon_item['price']);
                    }else{
                        $coupon_item['price'] = '';
                    }
                    $price_info = ['now_price'=>$price,'coupon'=>$coupon_item['price']];
                }else{
                    $price_info = ['now_price'=>$price,'coupon'=>''];
                }
            }
            $setting = self::getRewardByWhere(['themeid'=>$themeid]);
            $other_config = json_decode($setting['other_config'],true);
            $school_other_name = $other_config['school_other_name'];
            $course_other_name = $other_config['course_other_name'];
            $gift_other_name = $other_config['gift_other_name'];
            return [
                'form'=>$form,
                'theme_status'=>$theme_status,
                'price_info'=>$price_info,
                'school_other_name'=>$school_other_name,
                'course_other_name'=>$course_other_name,
                'gift_other_name'=>$gift_other_name,
            ];
        }
    }

    /**
     * Desc:获取用户所有的课程地址选择记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/13 11:56
     * @param $where
     * @return mixed
     */
    public static function getUserAllCourseAddress($where)
    {
        return db_getall(t_shangjia_address_user_course,$where);
    }

    public static function About($themeid,$system,$config,$fans,$op)
    {
        global $_P, $_G;
        if ($op=='display'){
            $where = ['uid'=>$fans['uid'],'themeid'=>$themeid];
            $has_flag = self::getCompanyInfoByWhere($where);
            return ['has_flag'=>$has_flag];
        }else{
            $mobile = isset($_P['mobile'])?$_P['mobile']:'';
            $username = isset($_P['username'])?$_P['username']:'';
            $company_name = isset($_P['company_name'])?$_P['company_name']:'';
            $address = isset($_P['address'])?$_P['address']:'';
            $type = 2;
            if ($company_name){
                $type=1;
            }
            $insert_data = [
                'uid'=>$fans['uid'],
                'mobile'=>$mobile,
                'username'=>$username,
                'company_name'=>$company_name,
                'address'=>$address,
                'type'=>$type,
                'themeid'=>$themeid
            ];
            $res = self::insertCompanyInfo($insert_data);

            if (!$res){
                return_json(1,'保存失败，请重试',[]);
            }else{
                return_json(0,'',[]);
            }
        }
    }

    public static function Gift($themeid)
    {
        //免费礼品
        $free = self::getGiftList($themeid,0,'',0,0,0,1);
        //获取可选礼品数量
        $setting = self::getRewardByWhere(['themeid'=>$themeid]);
        $gift_min_num = $setting['gift_min_num'];
        $gift_max_num = $setting['gift_max_num'];
        $setting = self::getRewardByWhere(['themeid'=>$themeid]);
        $other_config = json_decode($setting['other_config'],true);
        $gift_other_name = $other_config['gift_other_name'];
        return [
            'free'=>$free,
            'setting'=>$setting,
            'gift_min_num'=>$gift_min_num,
            'gift_max_num'=>$gift_max_num,
            'gift_other_name'=>$gift_other_name,
        ];
    }

    /**
     * Desc:获取归属于次分类的商家数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/9/3 16:46
     * @param $category_id
     * @return mixed
     */
    public static function getCategorySjTotal($category_id)
    {
        $sql = " select count(*) as cnt from ".tablename(t_shangjia)." where shangjia_rule_id='$category_id' ";
        return db_find($sql)['cnt'];
    }

    public static function Course($themeid,$user_location)
    {
        //获取可选课程数量
        $setting = self::getRewardByWhere(['themeid'=>$themeid]);
        $course_min_num = (int)$setting['course_min_num'];
        $course_max_num = (int)$setting['course_max_num'];
        $course_style = (int)$setting['course_style'];
        $open_shangjia_rules = ($course_style==3 || $course_style==4)?1:0;
        if ($open_shangjia_rules==1){
            $open_shangjia_rules = count(EducationModel::getCategoryListBy(['themeid'=>$themeid]))>0?1:0;
        }

        $other_config = json_decode($setting['other_config'],true);
        $school_other_name = $other_config['school_other_name'];
        $course_other_name = $other_config['course_other_name'];
        $gift_other_name = $other_config['gift_other_name'];
        $course_mode = $other_config['course_mode'];
        $show_buy_total = $other_config['show_buy_total'];
        $open_position = $other_config['open_position'];
        $edu_success_location_tips = $other_config['edu_success_location_tips'];
        $edu_location_show = $other_config['edu_location_show'];

        $colors = json_decode($setting['colors'],true);


        //获取分类
        if ($open_shangjia_rules==1){
            //二级分类
            //二级分类下设定数组
            $ct_shangjia_list = [];
            //获取一级主分类
            $first_list = EducationModel::getCategoryListBy(['themeid'=>$themeid,'pid'=>0]);
            foreach ($first_list as $e => $l){
                $temp_arr = ['id'=>$l['ct_id'],'title'=>$l['ct_name'],
                    'is_special'=>($l['ct_sj']==0&&$l['ct_sj_min']==0) ?1:0,'rule_sort'=>$l['ct_sort'],'has_child'=>0,'list_info'=>[],'ct_sj'=>$l['ct_sj'],'ct_sj_min'=>$l['ct_sj_min']];
                array_push($ct_shangjia_list,$temp_arr);
            }
            //排序
            $sort_filed = array_column($ct_shangjia_list,'rule_sort');
            array_multisort($sort_filed,SORT_ASC,$ct_shangjia_list);
        }
        //获取全部可选课程
        $course_list = self::getCourseList($themeid,0,'',0,0,1);
        //建立前端展示的商家 数组
        $show_shangjia_arr = [];
        foreach ($course_list as $key => $val)
        {
            $course_list[$key]['address'] = json_decode($val['address'],true);
            $course_list[$key]['mappoint'] = json_decode($val['mappoint'],true);
            if (!in_array($val['shangjia_id'],$show_shangjia_arr)){
                array_push($show_shangjia_arr,$val['shangjia_id']);
            }
            //课程选择数 真实加虚拟
            $course_list[$key]['selected_num'] = $val['selected_num']+self::getCourseFlagNum($themeid,$val['id']);
        }
        //格式化前端展示商家数组 ['shnagjia_id'=>1,'course_min'=>0,'course_max'=>1]
        $show_shangjia_data = [];
        foreach ($show_shangjia_arr as $key =>$val){
            $item = EducationModel::getShangjiaItem($val);
            if ($item){
                $item_other_config = json_decode($item['other_config'],true);
                $tmp_arr = ['shangjia_id'=>(int)$val,'course_min'=>(int)$item_other_config['course_min'],'course_max'=>(int)$item_other_config['course_max']];
                array_push($show_shangjia_data,$tmp_arr);
            }
        }
        $show_shangjia_data = json_encode($show_shangjia_data);
        //格式化前端展示分类数组
        $show_shangjia_category = [];
        $category_list = EducationModel::getCategoryListBy(['themeid'=>$themeid]);
        foreach ($category_list as $kb => $vb){
            $category_sj_total = self::getCategorySjTotal($l['id']);
            $tmp_ar = ['ct_id'=>(int)$vb['ct_id'],'ct_sj'=>(int)$vb['ct_sj'],'sj_total'=>$category_sj_total,
                'ct_sj_min'=>(int)$vb['ct_sj_min'],'ct_sort'=>$vb['ct_sort'],'ct_name'=>$vb['ct_name'],'is_first'=>$vb['pid']==0?1:0];
            array_push($show_shangjia_category,$tmp_ar);
        }
        $ttmp_Arr = array_column($show_shangjia_category, 'ct_sort');
        array_multisort($ttmp_Arr,SORT_ASC,$show_shangjia_category);

        $show_shangjia_category = json_encode($show_shangjia_category);

        //商家arr
        $shangjia = EducationModel::getShangjiaList();

        $shangjia_arr = [];

        foreach ($shangjia as $kk => $vv){
            $sj_course_total = EducationModel::getCourseTotal($themeid,$vv['id'],1);
            if ($sj_course_total>0){
                $temp_arr = ['id'=>$vv['id'],'title'=>$vv['name'],'displayorder'=>$vv['displayorder']];
                array_push($shangjia_arr,$temp_arr);
            }
        }
        //排序
        $sort_filed = array_column($shangjia_arr,'displayorder');
        array_multisort($sort_filed,SORT_ASC,$shangjia_arr);

        //二次遍历 商家
        foreach ($shangjia_arr as $k1 => $v1){
            foreach ($course_list as $k2 => $v2){
                if ($v1['id']==$v2['shangjia_id']){
                    $shangjia_arr[$k1]['courses'][] = $v2;
                }
            }
        }
        if ($open_shangjia_rules==1){
            //二级分类
            foreach ($ct_shangjia_list as $kd => $vd){
                //判断以及分类是否存在二级类
                $child = EducationModel::getCategoryListBy(['themeid'=>$themeid,'pid'=>$vd['id']]);
                if ($child){
                    //存在
                    $ct_shangjia_list[$kd]['has_child'] = count($child);
                    foreach ($child as $kd1 => $vd1){
                        $ct_shangjia_list[$kd]['list_info'][$kd1]['title'] = $vd1['ct_name'];
                        $ct_shangjia_list[$kd]['list_info'][$kd1]['firid'] = (int)$vd['id'];
                        foreach ($course_list as $kd2 => $vd2){
                            if ($course_style==4){
                                if ($vd1['ct_id']==$vd2['shangjia_category_id']){
                                    $ct_shangjia_list[$kd]['list_info'][$kd1]['courses'][] = $vd2;
                                    $ct_shangjia_list[$kd]['list_info'][$kd1]['secid'] = (int)$vd1['ct_id'];
                                    $ct_shangjia_list[$kd]['list_info'][$kd1]['ct_sj_min'] = (int)$vd1['ct_sj_min'];
                                    $ct_shangjia_list[$kd]['list_info'][$kd1]['ct_sj'] = (int)$vd1['ct_sj'];
                                }
                            }else{
                                if ($vd1['ct_id']==$vd2['shangjia_rule_id']){
                                    $ct_shangjia_list[$kd]['list_info'][$kd1]['courses'][] = $vd2;
                                    $ct_shangjia_list[$kd]['list_info'][$kd1]['secid'] = (int)$vd1['ct_id'];
                                    $ct_shangjia_list[$kd]['list_info'][$kd1]['ct_sj_min'] = (int)$vd1['ct_sj_min'];
                                    $ct_shangjia_list[$kd]['list_info'][$kd1]['ct_sj'] = (int)$vd1['ct_sj'];
                                }
                            }

                        }
                    }
                }else{
                    //不存在
                    $ct_shangjia_list[$kd]['has_child'] = 1;
                    $tmp_arr_1 = [];
                    foreach ($course_list as $kd2 => $vd2){
                        if ($vd['id']==$vd2['shangjia_rule_id']){
                            array_push($tmp_arr_1,$vd2);
                        }
                    }
                    if (count($tmp_arr_1)<1){
                        $ct_shangjia_list[$kd]['has_child'] = 0;
                    }
                    $tt_arr = ['title'=>$vd['title'],'courses'=>$tmp_arr_1,'firid'=>(int)$vd['id'],'secid'=>0,
                        'ct_sj_min'=>$vd['ct_sj_min'],
                        'ct_sj'=>$vd['ct_sj']
                    ];
                    $ct_shangjia_list[$kd]['list_info'][0] = $tt_arr;
                }
            }
        }

        //通过定位排序  距离由近到远
        if ($user_location){
            foreach ($course_list as $kk => $vv){
                if ($vv['mappoint'] && $vv['address'] && is_array($vv['mappoint'])){
                    $distance_arr = [];
                    foreach ($vv['mappoint'] as $k1 => $v1){
                        $distance_item = self::distance($v1,$user_location);
                        array_push($distance_arr,$distance_item);
                    }
                    $course_list[$kk]['min_distance'] = min($distance_arr);
                }else{
                    $course_list[$kk]['min_distance'] = 50;
                }
            }
            $sort_filed = array_column($course_list,'min_distance');
            if (count($course_list)>0){
                $course_list = Ad::arraySort($course_list,'min_distance','asc');
            }
            //二次 遍历机构类型数据
            foreach ($shangjia_arr as $kkk => $vvv){
                $item_temp_courese = $vvv['courses'];
                if ($item_temp_courese && is_array($item_temp_courese)){
                    foreach ($item_temp_courese as $kv => $vk){
                        if (!is_array($vk['mappoint'])){
                            $vk['mappoint'] = json_decode($vk['mappoint'],true);
                        }
                        if ($vk['mappoint'] && $vk['address'] && is_array($vk['mappoint'])){
                            $distance_arr = [];
                            foreach ($vk['mappoint'] as $k11 => $v11){
                                $distance_item = EducationModel::distance($v11,$user_location);
                                array_push($distance_arr,$distance_item);
                            }
                            $item_temp_courese[$kv]['min_distance'] = min($distance_arr);
                            $shangjia_arr[$kkk]['min_distance'] = min($distance_arr);
                        }
                    }
                    $shangjia_arr[$kkk]['courses'] = Ad::arraySort($item_temp_courese,'min_distance','asc');
                }
            }
            $sort_filed1 = array_column($shangjia_arr,'min_distance');
            if (count($shangjia_arr)>0){
                $shangjia_arr = Ad::arraySort($shangjia_arr,'min_distance','asc');
            }

            if ($open_shangjia_rules==1){
                //二次遍历 两级分类下的机构商家课程
                foreach ($ct_shangjia_list as $ff => $gg){
                    $tmp_gg = $gg['list_info'];
                    if (isset($tmp_gg)){
                        foreach ($tmp_gg as $rr => $tt){
                            if (isset($tt['courses']) && count($tt['courses'])>0){
                                $items_course_tmp = $tt['courses'];
                                foreach ($items_course_tmp as $kv1 => $vk1){
                                    if ($vk1['mappoint'] && $vk1['address'] && is_array($vk1['mappoint'])){
                                        $distance_arr = [];
                                        foreach ($vk1['mappoint'] as $k111 => $v111){
                                            $distance_item = EducationModel::distance($v111,$user_location);
                                            array_push($distance_arr,$distance_item);
                                        }
                                        $ct_shangjia_list[$ff]['list_info'][$rr]['courses'][$kv1]['min_distance'] = min($distance_arr);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if ($open_shangjia_rules==1){
            foreach ($ct_shangjia_list as $ww => $ee){
                $list_info_tmp = $ee['list_info'];
                if ($ee['has_child']>0){
                    foreach ($list_info_tmp as $bb => $mm){
                        if (!isset($mm['courses'])){
                            $ct_shangjia_list[$ww]['list_info'][$bb]['courses']=[];
                        }
                        if (!isset($mm['secid'])){
                            $ct_shangjia_list[$ww]['list_info'][$bb]['secid']=0;
                        }
                    }
                }
            }
        }
        //针对于分类下的定位距离排序
        if ($user_location && $ct_shangjia_list){
            foreach ($ct_shangjia_list as $k => $v){
                if ($v['list_info']){
                    $tmp_list_info = $v['list_info'];
                    foreach ($tmp_list_info as $k1 => $v1){
                        $tmp_courses = $v1['courses'];
                        if ($tmp_courses && is_array($tmp_courses)){
                            if (count($tmp_courses)>0){
                                array_multisort(array_column($tmp_courses,'min_distance'),SORT_ASC,array_column($tmp_courses,'shangjiaid'),SORT_ASC,$tmp_courses);
                            }
                            $ct_shangjia_list[$k]['list_info'][$k1]['courses'] = $tmp_courses;
                        }
                    }
                }
            }
        }
        //赠品判断
        $free = self::getGiftList($themeid,0,'',0,0,0,1);
        $gift_total = count($free);
        //判断用户是否开启商家分类
        return [
            'course_list'=>$course_list,
            'shangjia_arr'=>$shangjia_arr,
            'course_min_num'=>$course_min_num,
            'course_max_num'=>$course_max_num,
            'course_style'=>$course_style,
            'open_shangjia_rules'=>$open_shangjia_rules,
            'edu_colors'=>$colors,
            'gift_total'=>$gift_total,
            'show_shangjia_data'=>$show_shangjia_data,
            'ct_shangjia_list'=>$ct_shangjia_list,
            'school_other_name'=>$school_other_name,
            'course_other_name'=>$course_other_name,
            'show_shangjia_category'=>$show_shangjia_category,
            'show_buy_total'=>$show_buy_total,
            'course_mode'=>$course_mode,
            'gift_other_name'=>$gift_other_name,
            'open_position'=>$open_position,
            'edu_location_show'=>$edu_location_show,
            'edu_success_location_tips'=>$edu_success_location_tips,
        ];
    }

    public static function Reword($themeid,$theme,$system,$fans)
    {
        global $_P, $_G;
        $item = self::getRewardByWhere(['themeid'=>$themeid]);
        $item['tuan'] = json_decode($item['tuan'],true);
        $item['order'] = json_decode($item['order'],true);
        $temp_arr = [];
        $temp_total_arr = [];
        $other_config = json_decode($item['other_config'],true);
        $gift_none_btn_txt = $other_config['gift_none_btn_txt'];
        $gift_has_btn_txt = $other_config['gift_has_btn_txt'];

        if ($item['tuan'] && is_array($item['tuan'])){
            foreach ($item['tuan'] as $key => $val)
            {
                if ($val['key']=='主图'){
                    $temp_arr['img'] = $val['val'];
                }
                if ($val['key']=='提供商家'){
                    $temp_arr['shangjia'] = $val['val'];
                }
                if ($val['key']=='奖品'){
                    $temp_arr['title'] = $val['val'];
                }
                if ($val['key']=='价值'){
                    $temp_arr['price'] = $val['val'];
                }
                if ($val['key']=='奖励描述'){
                    $temp_arr['detail'] = $val['val'];
                }
                if ($val['key']=='id'){
                    $temp_arr['id'] = $val['val'];
                }
                $temp_arr['type'] = 'tuan';
                $temp_arr['from'] = '成团解锁(团长)';
                $temp_arr['invite_desc'] = '成功购买课程后，组团成功后解锁';
                $temp_arr['verify'] = false;
                $temp_arr['qrcode'] = '';
            }
            $themyrecord = Record::getLastGroupByUid($fans['uid'],$themeid);
            $has_gift =self::checkUserHasGift($themeid,$temp_arr['id'],$fans['uid']);
            if ($themyrecord && $themyrecord['type']==0 && $themyrecord['status']>0 && $themyrecord['isfinish']==1){
                if ($has_gift){
                    $temp_arr['bl_txt'] = '已解锁';
                    if ($has_gift['workerid']){
                        $temp_arr['br_txt'] = '已核销';
                        $temp_arr['verify'] = true;
                    }else{
                        $temp_arr['br_txt'] = $gift_has_btn_txt;
                        $temp_arr['qrcode'] = $_G['siteroot'].createMobileUrl('wx',array('themeid'=>$themeid,'from'=>'mobile','r'=>'education.index.Verify','mobile'=>$themyrecord['mobile'],'gift_id'=>$val['id'],'op'=>'display'));
                    }
                    $temp_arr['user_has'] = true;
                }else{
                    $temp_arr['bl_txt'] = '未解锁';
                    $temp_arr['br_txt'] = $gift_none_btn_txt;
                    $temp_arr['user_has'] = false;
                }
            }else{
                if ($themyrecord['type']!=1){
                    $temp_arr['bl_txt'] = '未解锁';
                    $temp_arr['br_txt'] = $gift_none_btn_txt;
                    $temp_arr['user_has'] = false;
                }
            }
            if (isset($temp_arr['bl_txt']) && $temp_arr['bl_txt']){
                array_push($temp_total_arr,$temp_arr);
            }

        }
        if ($item['order'] && is_array($item['order'])){
            $friend_order_total = (int)self::getFriendOrderTotal($themeid,$fans['uid'],1,$themyrecord['pid']);

            $setting = self::getRewardByWhere(['themeid'=>$themeid]);
            $tuan_gift_info = json_decode($setting['tuan'],true);
            $tuan_gift_id = '';
            if ($tuan_gift_info){
                foreach ($tuan_gift_info as $key => $val){
                    if ($val['key']=='id'){
                        $tuan_gift_id = $val['val'];
                    }
                }
            }

            //检查用户是否存在记录
            $check_tuan_gift = self::checkUserHasGift($themeid,$tuan_gift_id,$fans['uid']);

            foreach ($item['order'] as $key => $val){
                $temp_array = [];
                $temp_array['img'] = $val['img'];
                $temp_array['shangjia'] = $val['shangjia_name'];
                $temp_array['title'] = $val['name'];
                $temp_array['price'] = $val['price'];
                $tmp_str = '成团';
                if ($other_config['lock_gift_type']){
                    $tmp_str = '下单';
                }
                $temp_array['from'] = $tmp_str.'后累计邀请'.$val['invite'].'人解锁';
                $temp_array['type'] = 'order';
                $temp_array['detail'] = $val['detail'];
                $temp_array['invite_desc'] = $val['invite_desc'];
                $temp_arr['verify'] = false;
                $temp_arr['qrcode'] = '';
                $has_gift =EducationModel::checkUserHasGift($themeid,$val['gift_id'],$fans['uid']);
                if ($friend_order_total && ($friend_order_total>=(int)$val['invite']) && $check_tuan_gift){
                    $temp_array['bl_txt'] = '已解锁';
                    if ($has_gift && $has_gift['workerid']){
                        $temp_array['bl_txt'] = '已核销';
                        $temp_array['br_txt'] = '已核销';
                        $temp_arr['verify'] = true;
                    }else{
                        $temp_array['br_txt'] = $gift_has_btn_txt;
                        $temp_arr['qrcode'] = $_G['siteroot'].createMobileUrl('wx',array('themeid'=>$themeid,'from'=>'mobile','r'=>'education.index.Verify','mobile'=>$themyrecord['mobile'],'gift_id'=>$val['gift_id'],'op'=>'display'));
                    }
                    $temp_array['user_has'] = true;
                }else{
                    if ($friend_order_total && ($friend_order_total>=(int)$val['invite'])){
                        $temp_array['bl_txt'] = '已解锁';
                        $temp_array['br_txt'] = $gift_has_btn_txt;
                        $temp_array['user_has'] = true;
                    }else{
                        $temp_array['bl_txt'] = '未解锁';
                        $temp_array['br_txt'] = $gift_none_btn_txt;
                        $temp_array['user_has'] = false;
                    }

                }
                array_push($temp_total_arr,$temp_array);
            }
        }
        //赠品list
        $free = self::getGiftList($themeid,0,'',0,0,0,1);
        $user_free_gifts = self::getFreeFlag($fans['uid'],$themeid);
        $free_arr = [];
        if ($user_free_gifts){
            foreach ($user_free_gifts as $key => $val)
            {
                array_push($free_arr,$val['gift_id']);
            }
        }

        if ($free && is_array($free)){

            foreach ($free as $key => $val){
                $temp_arr = [];
                $temp_arr['img'] = $val['top_img'];
                $temp_arr['shangjia'] = $val['shangjia_name'];
                $temp_arr['title'] = $val['name'];
                $temp_arr['price'] = $val['price'];
                $temp_arr['from'] = '购买解锁';
                $temp_arr['type'] = 'free';
                $temp_arr['detail'] = $val['detail'];
                $temp_arr['invite_desc'] = '成功购买课程后解锁';
                $temp_arr['verify'] = false;
                $temp_arr['qrcode'] = '';
                if (is_array($free_arr) && in_array($val['id'],$free_arr)){
                    $gift_item = db_get(t_shangjia_user_gift,['themeid'=>$themeid,'uid'=>$fans['uid'],'gift_id'=>$val['id']]);
                    $temp_arr['bl_txt'] = '已解锁';
                    if ($gift_item && $gift_item['workerid']){
                        $temp_arr['br_txt'] = '已核销';
                        $temp_arr['verify'] = true;
                    }else{
                        $temp_arr['br_txt'] = $gift_has_btn_txt;
                        $temp_arr['qrcode'] = $_G['siteroot'].createMobileUrl('wx',array('themeid'=>$themeid,'from'=>'mobile','r'=>'education.index.Verify','mobile'=>$themyrecord['mobile'],'gift_id'=>$val['id'],'op'=>'display'));
                    }
                    $temp_arr['user_has'] = true;
                }else{
                    $temp_arr['bl_txt'] = '未解锁';
                    $temp_arr['br_txt'] = '免费获取';
                    $temp_arr['user_has'] = false;
                }
                array_unshift($temp_total_arr,$temp_arr);
            }
        }

        $themyrecord = Record::getLastGroupByUid($fans['uid'],$themeid);
        //海报地址
        //判断员工
        $myworker = Worker::getThemeWorkerByOpenid($_G['openid'],$themeid,1);
        $item = self::getRewardByWhere(['themeid'=>$themeid]);
        $poster_show = $item['poster_show'];
        $poster = Poster::getByThemeIdnew($themeid);
        if(!empty($poster['bg'])){
            $config['isposter']=1;
            if ($fans['status']==2 && $system['s']['istubiao']==1) {
                $config['isposter']=0;
            }
            $pm = ['themeid'=>$themeid,'openid'=>$fans['openid']];
            $myposter = db_find("SELECT * FROM ".tablename(t_fans)."
         WHERE themeid = :themeid and openid = :openid",$pm);
            if (empty($myposter['poster'])){
                $waittips = empty($poster['waittips'])?'正在生成海报':$poster['waittips'];
            }else{
                $waittips='';
            }
            //获取海报的url地址
            $posterurl = "/" . createMobileUrl("poster",array("themeid"=>$themeid,"op"=>"action","fromuid"=>$_P['fromuid'],"fopenid"=>$_P['fopenid'],"recordid"=>intval($themyrecord['id'])));

        }else{
            $waittips='海报未开启';
        }
        $pn_wxapp = $system['pn_wxapp'];
        if (!$pn_wxapp || $pn_wxapp==0){
            //        能否分享
            $canshare = 1;
            //       成功购买后生成
            if ($poster_show==2 && !$myworker && !$themyrecord){
                $waittips = '成功购买课程后，才能生成海报';
                $posterurl = '';
                $canshare = 0;
            }
        }else{
            if ($pn_wxapp==1){
                $canshare = 0;
            }elseif ($pn_wxapp==2){
                $canshare = 1;
            }elseif ($pn_wxapp==3){
                //        能否分享
                $canshare = 1;
                //       成功购买后生成
                if (!$myworker && !$themyrecord){
                    $waittips = '成功购买课程后，才能生成海报';
                    $posterurl = '';
                    $canshare = 0;
                }
            }
        }
        $poster_info = ['tips'=>$waittips,'img_url'=>$posterurl];
        //判断活动是否开始
        $start_theme = self::checkThemeStart($theme);
        //判断活动是否结束
        $end_theme = self::checkThemeEnd($theme);
        return [
            'canshare'=>$canshare,
            'temp_total_arr'=>$temp_total_arr,
            'poster_info'=>$poster_info,
            'verify_code'=>$verify_code,
            'start_theme'=>$start_theme,
            'end_theme'=>$end_theme,
        ];
    }

    public static function MineCourse($themeid,$system,$themyrecord,$fans)
    {
        global $_P, $_G;
        $_S = self::getSystem();
        $poster = Poster::getByThemeIdnew($themeid);
        if(!empty($poster['bg'])){
            $config['isposter']=1;
            if ($fans['status']==2 && $system['s']['istubiao']==1) {
                $config['isposter']=0;
            }
            $pm = ['themeid'=>$themeid,'openid'=>$fans['openid']];
            $myposter = db_find("SELECT * FROM ".tablename(t_fans)."
         WHERE themeid = :themeid and openid = :openid",$pm);
            if (empty($myposter['poster'])){
                $waittips = empty($poster['waittips'])?'正在生成海报':$poster['waittips'];
            }else{
                $waittips='';
            }
            //获取海报的url地址
            $posterurl = "/" . createMobileUrl("poster",array("themeid"=>$themeid,"op"=>"action","fromuid"=>$_P['fromuid'],"fopenid"=>$_P['fopenid'],"recordid"=>intval($themyrecord['id'])));

        }else{
            $waittips='海报未开启';
        }
        $item = self::getRewardByWhere(['themeid'=>$themeid]);
        $poster_show = $item['poster_show'];

        $myworker = Worker::getThemeWorkerByOpenid($_G['openid'],$themeid);
        $company_info = [];
        if ($myworker['company']){
            $company_info = self::getShangjiaItem($myworker['company']);
        }
        $pn_wxapp = $_S['pn_wxapp'];
        if (!$pn_wxapp || $pn_wxapp==0){
            //        能否分享
            $canshare = 1;
//       成功购买后生成
            if ($poster_show==2 && !$myworker && !$themyrecord){
                $waittips = '成功购买课程后，才能生成海报';
                $posterurl = '';
                $canshare = 0;
            }
        }else{
            if ($pn_wxapp==1){
                $canshare = 0;
            }elseif ($pn_wxapp==2){
                $canshare = 1;
            }elseif ($pn_wxapp==3){
                //        能否分享
                $canshare = 1;
                //       成功购买后生成
                if (!$myworker && !$themyrecord){
                    $waittips = '成功购买课程后，才能生成海报';
                    $posterurl = '';
                    $canshare = 0;
                }
            }
        }
        $poster_info = ['tips'=>$waittips,'img_url'=>$posterurl];

        $user_flag = [];
        if ($themyrecord){
            $user_flag = self::getUserCourseFlag($themeid,0,'',0,0,'','',$themyrecord['id']);
            foreach ($user_flag as $k => $v){
                if ($v['status'] && $v['workerid']){
                    $check_worker = db_get(t_worker,['themeid'=>$themeid,'uid'=>$v['workerid']]);
                    if ($check_worker){
                        $user_flag[$k]['workerid'] = $check_worker['username'];
                        $user_flag[$k]['qrcode'] = ''; //核销二维码

                    }
                }
                $user_flag[$k]['qrcode']  = $_G['siteroot'].createMobileUrl('wx',array('themeid'=>$themeid,'from'=>'mobile','r'=>'education.index.Verify','mobile'=>$themyrecord['mobile'],'flag_id'=>$v['id'],'op'=>'course'));
            }
        }
        $setting = self::getRewardByWhere(['themeid'=>$themeid]);
        $other_config = json_decode($setting['other_config'],true);
        $course_other_name = $other_config['course_other_name'];
        return [
            'canshare'=>$canshare,
            'poster_info'=>$poster_info,
            'user_flag'=>$user_flag,
            'company_info'=>$company_info,
            'course_other_name'=>$course_other_name,
        ];
    }

    /**
     * Desc:新增商家分类
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/22 11:44
     * @param $data
     * @return mixed
     */
    public static function insertCategory($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(t_shangjia_category,$data);
    }

    /**
     * Desc:修改商家分类
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/22 11:45
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function editCategory($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(t_shangjia_category,$data,$where);
    }

    /**
     * Desc:获取分类item
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/22 13:38
     * @param $where
     * @return mixed
     */
    public static function getCategory($where)
    {
        return db_get(t_shangjia_category,$where);
    }

    /**
     * Desc:获取查询条件下的分类
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/22 14:05
     * @param $where
     * @return mixed
     */
    public static function getCategoryListBy($where)
    {
        return db_getall(t_shangjia_category,$where);
    }

    /**
     * Desc:删除商家分类
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/22 11:45
     * @param $where
     * @return mixed
     */
    public static function delCategory($where)
    {
        return db_delete(t_shangjia_category,$where);
    }

    /**
     * Desc:获取查询条件下的分类列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/22 13:10
     * @param int $themeid
     * @param string $search
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public static function getCategoryList($themeid=1,$search='',$page_start=0,$page_size=10,$count = false)
    {
        $condition = "";
        if ($search){
            $condition .= " and ct_name LIKE'".$search."' ";
        }
        $condition .=" order by ct_sort asc ";
        if ($page_size && !$count) {
            $condition.= "LIMIT ".$page_start.",".$page_size;
        }
        $sql = "  from ".tablename(t_shangjia_category)." where themeid=$themeid ".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " select * ".$sql;
            return db_select($sql);
        }
    }

    /**
     * Desc:获取格式化分类数据
     * Author:cbw
     * Email:17854288794@163.com
     * Time: 2023/7/10 10:10
     * @param $themeid
     * @return array
     */
    public static function formatBackendData($themeid)
    {
        $list = self::getCategoryListBy(['themeid'=>$themeid,'pid'=>0]);
        $first = [];
        foreach ($list as $key => $val){
            array_push($first,$val);
            $child = self::getCategoryListBy(['themeid'=>$themeid,'pid'=>$val['ct_id']]);
            if ($child && is_array($child)){
                foreach ($child as $v){
                    $v['ct_name'] = $val['ct_name'].'['.$v['ct_name'].']';
                    array_push($first,$v);
                }
            }
        }
        return $first;
    }

    /**
     * Desc:设置定位
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2023/7/4 19:25
     * @param $themeid
     * @param $uid
     * @param $data
     * @return bool
     */
    public static function setUserMapLoc($themeid,$uid,$data)
    {
        $get_item = db_get(t_user_map_loc,['themeid'=>$themeid,'uid'=>$uid,'poiaddress'=>$data['poiaddress']]);
        if (!$get_item){
            $update_res = db_update(t_user_map_loc,['sort'=>0],['id >'=>0]);
            $format_data = [
                'themeid'=>$themeid,
                'uid'=>$uid,
                'cityname'=>$data['cityname'],
                'lat_lng'=>$data['lat'].','.$data['lng'],
                'lat'=>$data['lat'],
                'lng'=>$data['lng'],
                'sort'=>1,
                'poiaddress'=>$data['poiaddress'],
                'poiname'=>$data['poiname']
            ];
            $res = $insertid = db_insert(t_user_map_loc,$format_data);
            if(!$res){
                return false;
            }else{
                return true;
            }
        }else{
            $old_item_id = $get_item['id'];
            //修改
            $update_res = db_update(t_user_map_loc,['sort'=>0],['id >'=>0]);
            $new_update_res = db_update(t_user_map_loc,['sort'=>1],['id '=>$old_item_id]);
        }
        return true;
    }

    /**
     * Desc:查询用户最新的地位信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2023/7/4 19:19
     * @param $themeid
     * @param $uid
     * @return array
     */
    public static function getUserMapLoc($themeid,$uid)
    {
        $item = db_getall(t_user_map_loc,['themeid'=>$themeid,'uid'=>$uid],[],'',['sort desc'],[1,1]);
        if ($item && $item[0]){
            return $item[0];
        }
        return [];
    }
}